Created
August 22, 2017 15:57
-
-
Save Kelin2025/f611ab079cb895c4e91c2cf3a640b319 to your computer and use it in GitHub Desktop.
Apicase hooks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Container, ApiAbort } from 'apicase' | |
// For example, we have user info and validation schema for data | |
import user from './user' | |
import schema from './schema' | |
// For example we have route that create a new product | |
// And we have to sent title of product | |
const services = { | |
someService: { | |
method: 'POST', | |
url: '/products', | |
hooks: { | |
// We can check query before API call | |
// And cancel query on some problems | |
// To cancel query use | |
before ({ query }, next) { | |
let validation = Joi.validate(query, schema) | |
if (validation.error) { | |
return next(new ApiAbort(validation, { type: 'invalidForm' })) | |
} | |
next() | |
}, | |
// Redirect to created product after success | |
success (ctx) { | |
location.href = `/products/${ctx.result.id}` | |
}, | |
// Custom hook we made for form validation | |
invalidForm (ctx) { | |
console.log(ctx.reason) // Joi validate result | |
}, | |
// On another error | |
error (ctx) { | |
if (ctx.response.status === 401) { | |
alert('Oh no, you forgot to sign in') | |
return | |
} | |
alert('Some error happened') | |
}, | |
// I have a bad fantasy | |
// So let just console.log be here | |
finished (ctx) { | |
console.log('Finish') | |
} | |
} | |
}, | |
anotherService: { | |
method: 'DELETE', | |
url: '/products', | |
hooks: { | |
// You can pass array of hooks | |
// To separate semantic parts of handling | |
before: [ | |
// Check access | |
(ctx, next) => { | |
return user.isAdmin | |
? next() | |
: next(new ApiAbort('You are not admin', { name: 'Access denied' })) | |
}, | |
// Validate form | |
(ctx, next) => { | |
let validation = Joi.validate(ctx.query, schema) | |
return !validation.error | |
? next() | |
: next(new ApiAbort(validation, { name: 'Validation error' })) | |
} | |
], | |
// It also supports named hooks, yay! | |
error: [ | |
{ | |
name: 'Access denied', | |
handler (ctx) { | |
location.href = '/403' | |
} | |
}, | |
{ | |
name: 'Validation error', | |
handler (ctx) { | |
console.log(ctx.reason) | |
} | |
} | |
] | |
} | |
} | |
} | |
export default new Container({ | |
services | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment