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.
Related
I tried to Integrate OIDC Provider to Node JS and I have a Sample Code. So, I run this Sample code it's throwing an error(unrecognized route or not allowed method (GET on /api/v1/.well-known/openid-configuration)).The problem is Issuer(https://localhost:3000) this Issuer is working fine. but i will change this Issuer((https://localhost:3000/api/v1/)) it's not working How to fix this Issue and I facing another issue also when I implement oldc-provider in node js. They Routes are override how to fix this issue
Sample.js
const { Provider } = require('oidc-provider');
const configuration = {
// ... see available options /docs
clients: [{
client_id: 'foo',
client_secret: 'bar',
redirect_uris: ['http://localhost:3000/api/v1/'],
true_provider: "pcc"
// + other client properties
}],
};
const oidc = new Provider('http://localhost:3000/api/v1/', configuration);
// express/nodejs style application callback (req, res, next) for use with express apps, see /examples/express.js
oidc.callback()
// or just expose a server standalone, see /examples/standalone.js
const server = oidc.listen(3000, () => {
console.log('oidc-provider listening on port 3000, check http://localhost:3000/api/v1/.well-known/openid-configuration');
});
Error
Defining Issuer Identifier with a path component does not affect anything route-wise.
You have two options, either mount the provider to a path (see docs), or define the actual paths you want for each endpoint to be prefixed (see docs).
I think you're looking for a way to mount, so the first one.
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.
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
How would I automatically set the URL on an uploaded File in Keystone.js? This is the model for the File:
var keystone = require('keystone');
var Types = keystone.Field.Types;
var FileUpload = new keystone.List('FileUpload');
var myStorage = new keystone.Storage({
adapter: keystone.Storage.Adapters.FS,
fs: {
path: keystone.expandPath('./public/uploads/files'), // required; path where the files should be stored
publicPath: '/public/uploads/files', // path where files will be served
}
});
FileUpload.add({
name: { type: Types.Key, index: true},
file: {
type: Types.File,
storage: myStorage,
},
url: {type: String}
});
FileUpload.defaultColumns = 'name, url';
FileUpload.register();
I have tried to set the 'default' property of the url to something like
'/public/uploads/files/ + this.name
But the 'this' context is just an empty object literal. Keystone has an example in their docs where they make a custom frontend for uploading the images, and set the metadata of uploaded Files in a separate API call, but I'm trying to do this using their provided admin interface.
For clarification: you are trying make the entry in the Mongo database be the full path to the image not just the name of the image?
If I need something appended to the filename I do it on the template side, I guess you don't want to do that? Maybe if you explain the use case a little more?
I am new to Node.js. I wanted to add a simple validation for one of the form's field just to test the validation offered in Express. I followed the steps at https://www.npmjs.com/package/express-validation
I used express-validation middleware. I installed the appropriate modules(express-validation and joi).
Then I have added a folder "validation" and file "edit" with the following content:
var Joi = require('joi');
module.exports = {
body: {
title: Joi.string().required()
}
};
In the route that handles the post from the form I have added the appropriate parameter:
router.post('/', validate(validation.edit), function(req, res, next)
and saved the middleware and file with validation rule to the vars:
var validate = require('express-validation');
var validation = require('../validation/edit.js');
When I run the app it throws an error: Error('Please provide a validation schema').
So, I wonder what validation schema is required and where I suppose to add it?
The issue is with how you have your require defined. Since there is only one object in your edit.js module.exports, you do not need to call .edit on the validation. You can just do:
router.post('/', validate(validation), function(req, res, next)
Alternatively, you can define an index.js in your validation directory:
exports.edit = require('./edit');
Then require it:
var validation = require('../validation/');
And keep your middleware call the same as you had it. This will allow you to add more validation types easily, with only one require line. The project's test directory has a good example of this.