0.1.7 • Published 5 years ago
@zcong/koa-helpers v0.1.7
koa-helpers
helpers set for koa
Usage
error
const { ApiError, simpleErrorHandler } = require('@zcong/koa-helpers')
koa.use(simpleErrorHandler())
koa.use(ctx => {
throw new ApiError()
})
// will get
// {
// "code": "INTERNAL_ERROR",
// "message: "INTERNAL_ERROR",
// "messages": []
// }
password
const { hash, compare } = require('@zcong/koa-helpers')
const run = async () => {
const pass = 'password'
const hash = await hash(pass)
console.log(await compare(pass, hash)) // true
}
transform
const { transform } = require('@zcong/koa-helpers')
const post = {
'_id': 'uuid'
title: 'test',
content: 'test',
author: {
'_id': 'uuid',
name: 'user',
password: 'hashedpassword'
}
}
console.log(transform(post, {
omit: ['author._id', 'author.password'],
mapping: {
'_id': 'id'
}
}))
// output
// {
// id: 'uuid'
// title: 'test',
// content: 'test',
// author: {
// name: 'user'
// }
// }
validator
const Joi = require('joi')
const { validate } = require('@zcong/koa-helpers')
const schema = Joi.object().keys({
name: Joi.string()
.alphanum()
.min(6)
.required()
})
const run = async () => {
await validate({ name: 'test' }, schema) // throw new ApiError('INVALID_INPUT', 'INVALID_INPUT', 400, ['"name" length must be at least 6 characters long'])
}
License
MIT © zcong1993