fastify-papr-plugin
/
1.2.1
fastify-papr-plugin 1.2.1
Install from the command line:
Learn more about npm packages
$ npm install @flash-tecnologia/fastify-papr-plugin@1.2.1
Install via package.json:
"@flash-tecnologia/fastify-papr-plugin": "1.2.1"
About this version
yarn add @flash-tecnologia/fastify-papr-plugin @fastify/mongodb
Next, set up the plugin:
import fastifyMongodb from '@fastify/mongodb'
import fastifyPaprPlugin, { asModel, FastifyPaprOptions } from '@flash-tecnologia/fastify-papr-plugin'
import fp from 'fastify-plugin'
import { Model, schema, types } from 'papr'
const userSchema = schema({
name: types.string({ required: true, minLength: 10, maxLength: 100 }),
phone: types.string({ required: true, minLength: 8, maxLength: 20 }),
})
export type UserModel = Model<typeof userSchema[0], Partial<typeof userSchema[1]>>
declare module 'fastify' {
interface PaprModels {
user: UserModel
}
}
export default fp<FastifyPaprOptions>(
async (fastify) => {
await fastify.register(fastifyMongodb, {
url: 'mongodb://localhost:27017',
})
await fastify.register(fastifyPaprPlugin, {
db: fastify.mongo.client.db('test')),
models: { user: asModel('user', userSchema) },
})
},
{ name: 'papr' },
)
How to use:
import { FastifyPluginAsync } from 'fastify'
import { Static, Type } from '@sinclair/typebox'
const userDto = Type.Object({
name: Type.String({ maxLength: 100, minLength: 10 }),
phone: Type.String({ maxLength: 20, minLength: 7 }),
})
const userRoute: FastifyPluginAsync = async (fastify) => {
fastify.post<{ readonly Body: Static<typeof userDto> }>(
'/user',
{
schema: {
body: userDto,
},
},
async (req) => {
const result = await fastify.papr.user.insertOne(req.body)
return result
},
)
}
export default userRoute