Fastify系列【Swagger】

2019-05-18  本文已影响0人  老鱼_chaimyu

fastify记录备忘,特别感谢QD项目参考。

安装

fastify项目初始化

Chaim:employ-server Chaim$ npm init
Chaim:employ-server Chaim$ npm install fastify --save

fastify-swagger支持

npm i fastify-swagger --save

测试

const fastify = require('fastify')({ logger: true })

fastify.register(require('fastify-swagger'), {
  routePrefix: '/documentation',
  exposeRoute: true,
  swagger: {
    info: {
      title: 'Test swagger',
      description: 'testing the fastify swagger api',
      version: '0.1.0'
    },
    externalDocs: {
      url: 'https://swagger.io',
      description: 'Find more info here'
    },
    host: 'localhost',
    schemes: ['http'],
    consumes: ['application/json'],
    produces: ['application/json'],
    tags: [
      { name: 'user', description: 'User related end-points' },
      { name: 'code', description: 'Code related end-points' }
    ],
    securityDefinitions: {
      apiKey: {
        type: 'apiKey',
        name: 'apiKey',
        in: 'header'
      }
    }
  }
})

fastify.get('/test', {
    schema: {
      description: 'test data',
      tags: ['test'],
    }
}, async (request, reply) => {
  return { hello: 'world' }
});

fastify.ready(err => {
  if (err) throw err
  console.log("fastify swagger");
  fastify.swagger()
})

// Run the server!
const start = async () => {
  try {
    await fastify.listen(3000)
    fastify.log.info(`server listening on ${fastify.server.address().port}`)
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

启动

Chaim:employ-server Chaim$ node index

用浏览器访问"http://127.0.0.1:3000/test" 会返回"{"hello":"world"}",而访问"http://127.0.0.1:3000/documentation" 可以看到接口文档。

需要注意的是代码中一定要有"exposeRoute: true",否则不会输出接口文档。

正式

以上测试代码丢在一个文件里,比较混乱,可以按正规项目整理一下。

我们把源文件都放到src目录下,在src下分api、config等目录,目录结构如下:

image.png

config/swagger.js

'use strict';

module.exports = (fastify, opts, next) => {
  fastify.register(require('fastify-swagger'), {
    routePrefix: '/doc/api',
    exposeRoute: true,
    swagger: {
      info: {
        title: 'REST API Spec',
        description: 'api',
        version: '1.0.0'
      },
      host: 'localhost',
      schemes: ['http'],
      consumes: ['application/json'],
      produces: ['application/json'],
      securityDefinitions: {
        apiKey: {
          type: 'apiKey',
          name: 'apiKey',
          in: 'header'
        }
      }
    }
  });

  next();
}

api/routes/index.js

'use strict'

module.exports = (fastify, opts, next) => {
    fastify.register(require('./user'), { prefix: '/user'});
    next();
}

api/routes/user.js

'use strict';

async function login(req, reply) {
    let username = req.body.username;
    let password = req.body.password;

    return {
       errcode: 'SUCCESS', 
       token
    };
}

module.exports = (fastify, opts, next) => {
    fastify.post('/login', {
        schema: {
          description: '用户登录',
          tags: ['user'],
          body: {
           type: 'object',
           properties: {
             username: { type: 'string' },
             password: { type: 'string' },
           }
          }
        }
    }, login);

    next();
}

index.js

'use strict';

const fastify = require('fastify')({ logger: true })

const swapper = require('./config/swagger');
fastify.register(swapper);

fastify.register(require('./api/routes'), { prefix: '/v1' })

// Run the server!
const start = async () => {
  try {
    await fastify.listen(3000)
    fastify.log.info(`server listening on ${fastify.server.address().port}`)
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

看起来像样多了,再访问"http://127.0.0.1:3000/doc/api" 可以看到用户登录接口文档说明,如下:

image.png

跨域问题

但是测试接口时出现跨域错误,如下:

Access to fetch at 'http://localhost:3000/v1/worker/' from origin 'http://127.0.0.1:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

简单办法,安装fastify-cors

Chaim:employ-server Chaim$ npm i fastify-cors --save

加index.js中增加调用Fastify-cors

// 增加跨域支持
fastify.register(require('fastify-cors'), { 
  // put your options here
})

这样整个Fastify+Swagger就完整了,可以看到swagger页面并测试调用!

参考

https://cnpmjs.org/package/fastify-swagger

https://medium.freecodecamp.org/how-to-build-blazing-fast-rest-apis-with-node-js-mongodb-fastify-and-swagger-114e062db0c9

https://github.com/fastify/fastify-swagger

https://blog.csdn.net/freeboy1234/article/details/79289486

上一篇下一篇

猜你喜欢

热点阅读