Skip to content

Instantly share code, notes, and snippets.

@Kelin2025
Last active May 8, 2022 04:14
Show Gist options
  • Save Kelin2025/46bd3d091d07528b964540b4ea7fd24d to your computer and use it in GitHub Desktop.
Save Kelin2025/46bd3d091d07528b964540b4ea7fd24d to your computer and use it in GitHub Desktop.
Apicase example
import { Container } from 'apicase'
// Declare headers
const headers = () => ({
token: localStorage.getItem('token')
})
// Declare services
const services = {
hello: {
method: 'POST',
// path-to-regexp for URI params
url: '/hello/:id',
// Mixins for result getters
mixins: {
data () {
if (!this.ok) return null
return this.result.data
}
},
// koa-compose for hooks
hooks: {
// Before hook
// you can modify query before service call
// or abort it here
before (ctx, next) {
next({
...ctx,
additional: 'OK'
})
},
// After success call
success (ctx) {
console.log(ctx.query, ctx.result)
},
// If some error happened
error (ctx) {
console.log(ctx.response.status)
},
// After service call (no matter success or fail)
finished (ctx) {
console.log(ctx.response)
},
// If query was aborted in
aborted (ctx) {
console.log(ctx.reason)
},
// Your custom hook
// That you can call on abort in before hook
myCustomHook (ctx) {
console.log('Interesting')
}
}
}
}
// Global hooks if you want
const hooks = {
// You can also add array of hooks!
success: [
ctx => console.log('test 1'),
ctx => console.log('test 2')
],
// Or create named hooks
finished: {
name: 'My custom name',
handler (ctx) {
console.log(ctx)
}
}
}
// Create a container
const container = new Container({
base: '/api/v1',
headers,
services
})
// Service call
container.go('hello', { some: 'data' }, {
params: { id: 2 },
hooks: {
// And you can add hooks here too!
success (ctx) {
console.log(ctx)
}
}
})
// It's better to use async/await if no need in hooks
let res = await container.go('hello', { some: 'data' }, {
params: { id: 2 }
})
if (res.ok) {
console.log(res)
} else {
console.log('Oops!')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment