@JunQiu
2018-09-18T09:50:23.000000Z
字数 6798
阅读 2520
summary_2018/06 fastify
fastify.listen(3000, '127.0.0.1', 511, err => {if (err) {fastify.log.error(err)process.exit(1)}})fastify.listen(3000).then(() => console.log('Listening')).catch(err => {console.log('Error starting server:', err)process.exit(1)})
log(见fastify_log)
### Full declarationfastify.route(options)- method: currently it supports 'DELETE', 'GET', 'HEAD', 'PATCH', 'POST', 'PUT' and 'OPTIONS'. It could also be an array of methods.- url: the path of the url to match this route (alias: path).- schema: an object containing the schemas for the request and response. They need to be in JSON Schema format, check here for more info.- body: validates the body of the request if it is a POST or a PUT.- querystring: validates the querystring. This can be a complete JSON Schema object, with the property type of object and properties object of parameters, or simply the values of what would be contained in the properties object as shown below.- params: validates the params.- response: filter and generate a schema for the response, setting a schema allows us to have 10-20% more throughput.(生成请求体,加快响应速度)- beforeHandler(request, reply, done): a function called just before the request handler, useful if you need to perform authentication at route level for example, it could also be and array of functions.(在handler前处理)- handler(request, reply): the function that will handle this request.(处理请求的函数)- schemaCompiler(schema): the function that build the schema for the validations. See here- bodyLimit: prevents the default JSON body parser from parsing request bodies larger than this number of bytes. Must be an integer. You may also set this option globally when first creating the Fastify instance with fastify(options). Defaults to 1048576 (1 MiB).(请求体限制)- logLevel: set log level for this route. See below.- config: object used to store custom configuration.- request is defined in Request.- reply is defined in Reply.### Examplefastify.route({method: 'GET',url: '/',//参数检查schema: {querystring: {name: { type: 'string' },excitement: { type: 'integer' }},//生成请求response: {200: {type: 'object',properties: {hello: { type: 'string' }}}}},//处理请求的函数handler: function (request, reply) {reply.send({ hello: 'world' })}})### Shorthand declaration(类似express)//参数参考full declarationconst opts = {schema: {response: {200: {type: 'object',properties: {hello: { type: 'string' }}}}}}fastify.get('/', opts, (request, reply) => {reply.send({ hello: 'world' })})### Url buildingTips:Remember that static routes are always checked before parametric(参数的) and wildcard(通配符).// parametricfastify.get('/example/:userId', (request, reply) => {}))fastify.get('/example/:userId/:secretToken', (request, reply) => {}))// wildcard(可以使用正则表达式)fastify.get('/example/*', (request, reply) => {}))### use Async Awaitfastify.get('/', options, async function (request, reply) {var data = await getData()var processed = await processData(data)return processed})Tips:you can use return and reply.send,if you use at the same time ,the second value will be discarded### Route Prefixing// server.jsconst fastify = require('fastify')()fastify.register(require('./routes/v1/users'), { prefix: '/v1' })fastify.listen(3000)// routes/v1/users.jsmodule.exports = function (fastify, opts, next) {fastify.get('/user', handler_v1)next()}### Configfunction handler (req, reply) {reply.send(reply.context.config.output)}fastify.get('/en', { config: { output: 'hello world!' } }, handler)fastify.get('/it', { config: { output: 'ciao mondo!' } }, handler)
### logger optionconst fastify = require('fastify')({logger: {level: 'info',stream: stream}})### By default fastify adds an id to every request for easier tracking.//自己设置ID:genReqIdlet i = 0const fastify = require('fastify')({logger: {genReqId: function (req) { return i++ }}})### supply your own logger//You can also supply your own logger instance. Instead of passing configuration options, simply pass the instance. The logger you supply must conform to the Pino interface; that is, it must have the following methods: info, error, debug, fatal, warn, trace, child.const log = require('pino')({ level: 'info' })const fastify = require('fastify')({ logger: log })### 打印日志//request.log.warn//fastify.log.warn
### Exampleconst schema = {body: {type: 'object',required: ['someKey'], // 必须字段properties: {someKey: { type: 'string' },someOtherKey: { type: 'number' }}},querystring: {name: { type: 'string' },excitement: { type: 'integer' }},params: {type: 'object',properties: {par1: { type: 'string' },par2: { type: 'number' }}},}fastify.post('/the/url', { schema }, handler)//JSON Schemaconst querySchema = {schema: {querystring: { // 被废弃type、properties??type: 'object',properties: {name: {type: 'string'}},required: ['name']}}}### shared schema//you can add multiple schemas to the Fastify instance and then reuse them in multiple parts of your application. (Note that this API is not encapsulated)const fastify = require('fastify')()fastify.addSchema({$id: 'greetings',type: 'object',properties: {hello: { type: 'string' }}})fastify.route({method: 'POST',url: '/',schema: {body: 'greetings#'},handler: () => {}})### Schema Compiler(fastify use ajv speed the validation up)While you cannot change the configuration options of the default ajv instance, you can create your own:(创建自己的ajv instance)const fastify = require('fastify')()const Ajv = require('ajv')const ajv = new Ajv({// the fastify defaultsremoveAdditional: true,useDefaults: true,coerceTypes: true})fastify.setSchemaCompiler(function (schema) {return ajv.compile(schema)})### use other validation libraryconst Joi = require('joi')fastify.post('/the/url', {schema: {body: Joi.object().keys({hello: Joi.string().required()}).required()},schemaCompiler: schema => data => Joi.validate(data, schema)}, handler)
### Exampleconst schema = {response: {200: {type: 'object',properties: {value: { type: 'string' },otherValue: { type: 'boolean' }}}}}fastify.post('/the/url', { schema }, handler)### the response schema is based on the status code. If you want to use the same schema for multiple status codes, you can use '2xx''2xx': {type: 'object',properties: {value: { type: 'string' },otherValue: { type: 'boolean' }}}