[关闭]
@JunQiu 2018-09-18T09:50:23.000000Z 字数 6798 阅读 1983

fastify(route,method,Serialization,test,log)

summary_2018/06 fastify


1、日常工作


2、技术学习

  1. fastify.listen(3000, '127.0.0.1', 511, err => {
  2. if (err) {
  3. fastify.log.error(err)
  4. process.exit(1)
  5. }
  6. })
  7. fastify.listen(3000)
  8. .then(() => console.log('Listening'))
  9. .catch(err => {
  10. console.log('Error starting server:', err)
  11. process.exit(1)
  12. })
  1. ### Full declaration
  2. fastify.route(options)
  3. - method: currently it supports 'DELETE', 'GET', 'HEAD', 'PATCH', 'POST', 'PUT' and 'OPTIONS'. It could also be an array of methods.
  4. - url: the path of the url to match this route (alias: path).
  5. - schema: an object containing the schemas for the request and response. They need to be in JSON Schema format, check here for more info.
  6. - body: validates the body of the request if it is a POST or a PUT.
  7. - 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.
  8. - params: validates the params.
  9. - response: filter and generate a schema for the response, setting a schema allows us to have 10-20% more throughput.(生成请求体,加快响应速度)
  10. - 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前处理)
  11. - handler(request, reply): the function that will handle this request.(处理请求的函数)
  12. - schemaCompiler(schema): the function that build the schema for the validations. See here
  13. - 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).(请求体限制)
  14. - logLevel: set log level for this route. See below.
  15. - config: object used to store custom configuration.
  16. - request is defined in Request.
  17. - reply is defined in Reply.
  18. ### Example
  19. fastify.route({
  20. method: 'GET',
  21. url: '/',
  22. //参数检查
  23. schema: {
  24. querystring: {
  25. name: { type: 'string' },
  26. excitement: { type: 'integer' }
  27. },
  28. //生成请求
  29. response: {
  30. 200: {
  31. type: 'object',
  32. properties: {
  33. hello: { type: 'string' }
  34. }
  35. }
  36. }
  37. },
  38. //处理请求的函数
  39. handler: function (request, reply) {
  40. reply.send({ hello: 'world' })
  41. }
  42. })
  43. ### Shorthand declaration(类似express)
  44. //参数参考full declaration
  45. const opts = {
  46. schema: {
  47. response: {
  48. 200: {
  49. type: 'object',
  50. properties: {
  51. hello: { type: 'string' }
  52. }
  53. }
  54. }
  55. }
  56. }
  57. fastify.get('/', opts, (request, reply) => {
  58. reply.send({ hello: 'world' })
  59. })
  60. ### Url building
  61. Tips:Remember that static routes are always checked before parametric(参数的) and wildcard(通配符).
  62. // parametric
  63. fastify.get('/example/:userId', (request, reply) => {}))
  64. fastify.get('/example/:userId/:secretToken', (request, reply) => {}))
  65. // wildcard(可以使用正则表达式)
  66. fastify.get('/example/*', (request, reply) => {}))
  67. ### use Async Await
  68. fastify.get('/', options, async function (request, reply) {
  69. var data = await getData()
  70. var processed = await processData(data)
  71. return processed
  72. })
  73. Tips:you can use return and reply.send,if you use at the same time ,the second value will be discarded
  74. ### Route Prefixing
  75. // server.js
  76. const fastify = require('fastify')()
  77. fastify.register(require('./routes/v1/users'), { prefix: '/v1' })
  78. fastify.listen(3000)
  79. // routes/v1/users.js
  80. module.exports = function (fastify, opts, next) {
  81. fastify.get('/user', handler_v1)
  82. next()
  83. }
  84. ### Config
  85. function handler (req, reply) {
  86. reply.send(reply.context.config.output)
  87. }
  88. fastify.get('/en', { config: { output: 'hello world!' } }, handler)
  89. fastify.get('/it', { config: { output: 'ciao mondo!' } }, handler)
  1. ### logger option
  2. const fastify = require('fastify')({
  3. logger: {
  4. level: 'info',
  5. stream: stream
  6. }
  7. })
  8. ### By default fastify adds an id to every request for easier tracking.
  9. //自己设置ID:genReqId
  10. let i = 0
  11. const fastify = require('fastify')({
  12. logger: {
  13. genReqId: function (req) { return i++ }
  14. }
  15. })
  16. ### supply your own logger
  17. //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.
  18. const log = require('pino')({ level: 'info' })
  19. const fastify = require('fastify')({ logger: log })
  20. ### 打印日志
  21. //request.log.warn
  22. //fastify.log.warn
  1. ### Example
  2. const schema = {
  3. body: {
  4. type: 'object',
  5. required: ['someKey'], // 必须字段
  6. properties: {
  7. someKey: { type: 'string' },
  8. someOtherKey: { type: 'number' }
  9. }
  10. },
  11. querystring: {
  12. name: { type: 'string' },
  13. excitement: { type: 'integer' }
  14. },
  15. params: {
  16. type: 'object',
  17. properties: {
  18. par1: { type: 'string' },
  19. par2: { type: 'number' }
  20. }
  21. },
  22. }
  23. fastify.post('/the/url', { schema }, handler)
  24. //JSON Schema
  25. const querySchema = {
  26. schema: {
  27. querystring: { // 被废弃type、properties??
  28. type: 'object',
  29. properties: {
  30. name: {
  31. type: 'string'
  32. }
  33. },
  34. required: ['name']
  35. }
  36. }
  37. }
  38. ### shared schema
  39. //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)
  40. const fastify = require('fastify')()
  41. fastify.addSchema({
  42. $id: 'greetings',
  43. type: 'object',
  44. properties: {
  45. hello: { type: 'string' }
  46. }
  47. })
  48. fastify.route({
  49. method: 'POST',
  50. url: '/',
  51. schema: {
  52. body: 'greetings#'
  53. },
  54. handler: () => {}
  55. })
  56. ### Schema Compiler(fastify use ajv speed the validation up)
  57. While you cannot change the configuration options of the default ajv instance, you can create your own:(创建自己的ajv instance)
  58. const fastify = require('fastify')()
  59. const Ajv = require('ajv')
  60. const ajv = new Ajv({
  61. // the fastify defaults
  62. removeAdditional: true,
  63. useDefaults: true,
  64. coerceTypes: true
  65. })
  66. fastify.setSchemaCompiler(function (schema) {
  67. return ajv.compile(schema)
  68. })
  69. ### use other validation library
  70. const Joi = require('joi')
  71. fastify.post('/the/url', {
  72. schema: {
  73. body: Joi.object().keys({
  74. hello: Joi.string().required()
  75. }).required()
  76. },
  77. schemaCompiler: schema => data => Joi.validate(data, schema)
  78. }, handler)
  1. ### Example
  2. const schema = {
  3. response: {
  4. 200: {
  5. type: 'object',
  6. properties: {
  7. value: { type: 'string' },
  8. otherValue: { type: 'boolean' }
  9. }
  10. }
  11. }
  12. }
  13. fastify.post('/the/url', { schema }, handler)
  14. ### 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'
  15. '2xx': {
  16. type: 'object',
  17. properties: {
  18. value: { type: 'string' },
  19. otherValue: { type: 'boolean' }
  20. }
  21. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注