A fetch wrapper with repository pattern register
npm install fetch-repositoryThis is a simple library that consists in a fetch wrapper + repository pattern utility. You can use both together or in isolation.
Warning: This is a fresh idea that is evolving, and may contain bugs.
1. Using the Fetch Wrapper
2. Using the Repository API
``jsx
import { http } from 'fetch-repository'
// With promise
http
.get(url, config)
.then(result => {})
.catch(err => {})
// With async/await
async function getData() {
try {
const result = await http.get(url, config)
} catch (e) {
console.error(e)
}
}
`
`jsx
import { http, Repository } from 'fetch-repository'
Repository.add('Posts', {
get baseUrl() {
return 'https://jsonplaceholder.typicode.com/posts'
},
getAll() {
return http.get(this.baseUrl)
},
getById(id: number) {
return http.get(${this.baseUrl}/${id})`
},
create(body: object) {
return http.post(this.baseUrl, body)
},
})
Then, just consume it later:
`jsx
import { Repository } from 'fetch-repository'
const PostsRepository = Repository.get('Posts')
try {
const posts = await PostsRepository.getAll()
} catch (e) {
console.error(e)
}
``