Swageer js doc does not instant update api docs on changes? - node.js

I am using swagger-jsdoc
I have setup swagger js docs like below in my app.js
//include swagger js doc
var swaggerJSDoc = require('swagger-jsdoc');
const swaggerUi = require('swagger-ui-express');
const pathToSwaggerUi = require('swagger-ui-dist').absolutePath()
const swaggerDefinition = {
swagger: '2.0',
info: {
// API informations (required)
title: 'API', // Title (required)
version: '1.0.0', // Version (required)
description: 'Used for api documentation', // Description (optional)
},
host: `localhost:3000`, // Host (optional)
basePath: '/app/v1', // Base path (optional)
};
// Options for the swagger docs
const options = {
// Import swaggerDefinitions
swaggerDefinition,
// Path to the API docs
// Note that this path is relative to the current directory from which the Node.js is ran, not the application itself.
apis: ['./app/v1/docs/*.yaml']
};
// Initialize swagger-jsdoc -> returns validated swagger spec in json format
const swaggerSpec = swaggerJSDoc(options);
app.use('/v1/docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
I have certain yaml files which i have written for document the api. I hit the url from browser
localhost:3000/v1/docs
This shows me documented api in swagger ui. But when i make update in any of the yaml files and refresh the page then i don't see updated changes. I have to stop the nodemon process and restart the process again which i do not want to do. So let me know how can i do this?

By default, nodemon looks for files with the .js, .mjs, .coffee, .litcoffee, and .json extensions.
To add other extensions please use the following command:
nodemon -e yaml
For more details, refer to the official docs: https://www.npmjs.com/package/nodemon

Related

How to use Bolt events with the newer Slack API manifests?

I'm building a Slack App using Bolt and I've got the basics working using Socket Mode. The docs say that socket mode apps are not allowed in the public directory, which I do want my App in when it's ready. I've now turned off socket mode and got ngrok working as described here. Slack was able to validate the url anyway.
But what's not working is a slash command. The manifest editor says the url is required for a slash command, but how does that line up with bolt? Are there better docs for non-socket-mode somewhere? It seems like every example of using bolt says "let's use socket mode, it's easy".
Manifest portion:
slash_commands:
- command: /sb
url: https://[my url].ngrok.io/slack/command
Sample code:
const { App } = require('#slack/bolt');
const express = require('express');
const app = express();
const boltApp = new App({
signingSecret: config.slackApp.signingSecret,
token: config.slackApp.token,
endpoints = '/'
});
app.use('/slack/events', boltApp.receiver.router);
Bolt
Slack App Manifests
I got this working with a combination of the following:
setting every url in the manifest (slash_commands, event_subscriptions, interactivity) to https://foo.ngrok.io/slack/
attaching Bolt to an existing Express App, attempting to follow this PR to use app and/or router config prop on ExpressReceiver, but strangely what worked was putting the express app into the router
setting up Bolt like below
Example Code:
const expressApp = express();
...
const boltReceiver = new ExpressReceiver({
router: expressApp,
signingSecret: SLACK_SIGNING_SECRET,
endpoints: '/slack'
});
const boltApp = new App({
token: SLACK_BOT_TOKEN,
receiver: boltReceiver,
appToken: SLACK_APP_TOKEN,
socketMode: false,
});

Configure swagger with Nestjs + Azure functions

I am trying to develop my nestjs using azure functions following this article:
https://trilon.io/blog/deploy-nestjs-azure-functions
I have configured Swagger in my application as follows:
...
const options = new DocumentBuilder()
.setTitle('App title')
.setDescription('App description')
.setVersion('1.0')
.addBearerAuth(
{
type: 'http',
scheme: 'bearer',
bearerFormat: 'JWT',
},
'authorization',
)
.addTag('freight')
.build();
const document = SwaggerModule.createDocument(app, options);
SwaggerModule.setup('swagger', app, document);
...
When I run the app in development, I can access my swagger UI by navigating to /swagger, however when I run npm run build && func host start, I receive 500 error, which also happens when I hit a non-existing route.
All other routes that are registered in the application work as expected.
Nestjs has a module you need to load for this. nestjs-openapi
Next you will need to specify a few configuration items.
Note: Main.ts is not used at all.
Sync ports with:
func host start --port 3000
!! Use the app instance within the main.azure.ts. Example assumes global prefix defined above the code below.
...
//config
const config = new DocumentBuilder()
.setTitle('My Title')
.setDescription('My Description')
.setVersion('1.0')
.setBasePath('api-docs')
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api-docs', app, document, {
useGlobalPrefix: true,
});
// order matters here.
app.init()
// port that is used for swagger ui. Sync with Az Fx.
app.listen(3000)
Now you can route to localhost:3000/{global_prefix}/api-docs to load swagger ui.

How can my client get application configuration from the server when using Webpack?

I'm adding Webpack to a Node/Express app that previously used RequireJS. When the client needed some configuration from the server, we previously used a custom Express route that retrieved specific configs as JSON:
server/index.js - Set up Express routes for config files
const app = express();
const configRouter = express.Router();
configRouter.get('/some-config.json', (req, res) => {
const someConfig = {
prop1: getProp1(),
prop2: getProp2()
}
res.json(someConfig);
}
app.use('/config', configRouter);
client/controller.js - Use/config/some-config.json during initialization
define(['text!/config/some-config.json'], function(SomeConfig) {
// do something with SomeConfig
});
But removing RequireJS means I can no longer retrieve the JSON this way as a dependency. And it's not static JSON either, so it's not as simple as just placing it alongside client code and importing it.
So what is the best way to do this with Webpack? Any help greatly appreciated. Thanks!

Trying to Update Open API Spec from 2.0 to 3.0 But YAML Still Evaluates as 2.0.

I am trying to update my local swagger project from OpenAPI 2.0 to OpenAPI 3.0.
I am getting a ton of errors which imply that I my YAML file is still being evaluated as OAS2.0:
Project Errors
--------------
#/: Missing required property: swagger
#/: Additional properties not allowed: components,servers,openapi
#/paths/~1auth~1info~1firebase/get/responses/200: Not a valid response definition
#/paths/~1posts~1{id}~1comments/get/responses/200: Not a valid response definition
#/paths/~1posts~1{id}~1comments/get/parameters/2: Not a valid parameter definition
#/paths/~1posts~1{id}~1comments/get/parameters/1: Not a valid parameter definition
#/paths/~1posts~1{id}~1comments/get/parameters/0: Not a valid parameter definition
#/paths/~1users~1{id}~1profile/get/responses/200: Not a valid response definition
I have updated swagger-ui-express to the latest version.
Below are the relevant parts of my server.js file:
const YAML = require('yamljs');
const swaggerDocument = YAML.load('./api/swagger/swagger.yaml');
const SwaggerExpress = require('swagger-express-mw');
const swaggerUI = require('swagger-ui-express');
const api = express();
let swaggerConfig =
{
appRoot: __dirname
}
let swaggerOptions =
{
explorer: true
};
api.use('/api/v1/docs/endpoints',
swaggerUI.serve,
swaggerUI.setup(swaggerDocument, swaggerOptions)
);
SwaggerExpress.create(swaggerConfig, function(err, swaggerExpress) {
if (err) { throw err; }
// install middleware
swaggerExpress.register(api);
});
I have updated swagger-ui-express and swagger-express-mw to the latest versions.
But I am still getting the above errors.
I am thinking that the way forward may be to not use swagger-ui-express
and rework my code for swagger-ui but I see online that people seem to
get things working with that npm module.
Any ideas what I am doing wrong?

Validation of Express request based on Swagger YAML

Is out there a node module for validation of the schema/values provided in Express req object, based on Swagger YAML schema definition for that request?
Let's say this is relevant part of the YAML:
/books/{genre}:
get:
parameters:
- name: genre
in: path
required: true
type: string
- name: size
in: query
required: false
type: number
A req object derived from the following request should pass validation:
GET /books/sci-fi
GET /books/thriller?size=5
And this one should fail:
GET /books/12
To generate a template node.js server using a yaml file, try swagger.io > Swagger Editor > Online Editor > build your yaml in the left pane > Generate Server > Node.js
The downloadable package will use swagger-tools for validation. The default index.js in the generated code will define that your controllers (custom code to handle each request) will live in the controllers directory:
// swaggerRouter configuration
var options = {
swaggerUi: '/swagger.json',
controllers: './controllers',
useStubs: process.env.NODE_ENV === 'development' ? true : false // Conditionally turn on stubs (mock mode)
};
Add these elements to the endpoint definition to define the controller name and the method name:
You can add this property to your endpoint definition to tell the swagger-tools middleware which javascript file will handle the request:
x-swagger-router-controller: myController
operationId: myMethod
Create a controllers directory containing myController.js that exports myMethod:
module.exports.myMethod = myMethod;
function myMethod(req, res) {
//do stuff
res.end();
}
The inputs will be validated before the request is routed to your controller.

Resources