Comments (29)
There's a repository https://github.com/nestjs/swagger
Package is published as @nestjs/swagger
I'm creating the tutorial now
from nest.
Hi @Martodox,
Definitely needed! I'll make it in the future. Stay tuned 😄
from nest.
could you share the progress of the swagger documentation and tell us how we can help you?
from nest.
Hi guys,
Swagger module is in beta stage. Hope to share it with you asap 😃
from nest.
Here's an example https://docs.nestjs.com/recipes/swagger 🙂 I hope it's enough for now!
from nest.
@qinyang1980 one time 😄
@LuukMoret in progress 💪
from nest.
@Martodox hmm if there will be an solution to inject some "middleware" into http controllers, there will be option to create independent module for nest
to generate a swagger.json
file as output ;>
@kamilmysliwiec an extra events like hooks ;) hmmm ;>
from nest.
Hi,
here is example of basic usage:
@Controller('status')
@ApiUseTags("status") // OpenAPI tag property
export class StatusController {
@Get("/status")
@ApiOperation({title: "Returns API status"})
@ApiResponse({status: HttpStatus.OK, type: StatusModel, description: "Returns API status"})
@ApiResponse({status: "default", type: RequestException, description: "Error Response"})
async getStatus(@Req() req, @Res() res) {
return await this.statusService.getStatus();
}
}
//model definition
export class StatusModel {
@ApiModelProperty()
public status: string;
@ApiModelProperty()
public uptime: Date;
@ApiModelProperty({items: {type: 'string', enum: SomeEnum}})
public items: SomeEnum[];
}
export class RequestException {
@ApiModelProperty()
private readonly message: string;
@ApiModelProperty()
private readonly status: number;
constructor(message: string, status: number) {
this.message = message;
this.status = status
}
getMessage(): string {
return this.message;
}
getStatus(): number {
return this.status;
}
}
//server.ts
async function bootstrap() {
const express = require("express");
const swaggerUi = require('swagger-ui-express');
const server = express();
const app = await NestFactory.create(ApplicationModule, server);
let apiDoc = SwaggerModule.createDocument(app, {
//TODO: swagger: '2.0',
info: {
description: "OpenAPI",
version: "1.0.0",
title: "OpenAPI",
},
basePath: "/api"
});
apiDoc['swagger'] = '2.0';
server.get('/api-docs/swagger.json', function (req, res) { //swagger json
res.json(apiDoc);
});
server.use('/api-docs/ui', swaggerUi.serve, swaggerUi.setup(apiDoc)); //swagger ui
// SwaggerModule.setup('/api-docs/ui', app, apiDoc); //not working
}
bootstrap();
Hope it helps to start
from nest.
You can also see an example here. nestjs/swagger#4
from nest.
Cool @darioxtx, thank you. I ended up following a separate solution, based on the thread @Jorgevillada proposed, with some due modifications. Here my server.ts, it creates a http://localhost:3001/swagger
ui which interacts with the nest app at localhost 3000:
import * as bodyParser from 'body-parser';
import { NestFactory } from '@nestjs/core';
import { ApplicationModule } from './modules/app.module';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
const express = require('express');
const cors = require('cors');
const swaggerUI = require('swagger-ui-express');
const showExplorer = true;
const appHost = 'localhost:3000';
async function bootstrap() {
const app = await NestFactory.create(ApplicationModule);
const Eapp = express();
Eapp.use(cors());
app.use(cors());
app.use(bodyParser.json());
const documentBuilder = new DocumentBuilder();
documentBuilder.addBearerAuth('Authorization', 'header');
documentBuilder.setHost(appHost);
const document = SwaggerModule.createDocument(app, documentBuilder.build());
Eapp.use('/swagger', swaggerUI.serve, swaggerUI.setup(document));
Eapp.use('/api-docs', (req, res, next) => res.send(document));
await Eapp.listen(3001);
await app.listen(3000);
}
bootstrap();
from nest.
Amazing thread :)
quick question : how do you generate a static website of the documentation ? So far, it's only available when running the nest server. I don't wish to expose the swagger to everyone when starting the server.
from nest.
@kamilmysliwiec The project that I had started at work copied my approach from my another project: sample file with swagger-jsdoc. It does the job, but it would be cool to integrate it with TS decorators (just like java swing).
from nest.
@kamilmysliwiec any updates on swagger module ? maybe i can help at least in testing ?
from nest.
Hey guys. I have to say that Nest looks really good. Kudos to the dev team.
Good architecture, and learning curve is minimal if Angular is your background.
Not having swagger integration is a major issue though (pretty much the only issue I found so far).
Everyone who's got Angular skills will want to generate their client code and use swagger tooling.
Maintaining a swagger spec in sync manually is a nightmare, so if this issue could be fixed, then Nest ( combined with typeorm ) would probably be the ultimate way to go on the node side of things.
I am currently using TSOA which provides a swagger spec from the route decorators and it's fairly mature.
Decorators aren't too different from the ones on Nest. I didn't investigate how much of that code would be portable ?
Anyway, let me know if there's anything I can do to speed this up, as the above poster said, even if it's just testing.
from nest.
@irissoftworks I think Swagger integration is ready on release/v4 branch. I hope it would be ready soon to start playing with.
from nest.
Great! Apologies everyone, I went through the other branch yesterday, but I think I must have missed it.
I realized it was actually mentioned on the release ticket. If anyone else is looking, here is the ticket #120 .
Looking forward to it!
from nest.
@kamilmysliwiec how does v4 influence on this issue?
from nest.
Hi @cojack,
The @nestjs/swagger
package is in alpha version, I need to publish it as a separated repo 🙂
from nest.
@kamilmysliwiec waiting so much 👍
from nest.
@valorkin this is what Georgii needed for our swagger docs. :)
from nest.
As far as I know, swagger was renamed to Open API
from nest.
@kamilmysliwiec
Yup, would like to help too. Nestjs is a very good project. Slowly starting to enjoy writing Express API's with it :D. Thanks for your work, Kamil.
from nest.
@kamilmysliwiec any chance you can share the work in progress of the tutorial?
from nest.
Hello @darioxtx: 2 questions related to your answer (sorry for noobying, I am kind of new to nest :-)):
- how do you have access to (i.e., inject) the 'app' object within the swagger controller?
- what is the RequestException object?
Thank you!
from nest.
My bad, you should use SwaggerModule in app bootstrap function.
I updated example.
from nest.
@kamilmysliwiec, amazing work. This is just what I want.
You must have been a Java Spring Boot developer.
from nest.
@kamilmysliwiec Yes, very nice indeed! Any ETA on the GraphQL recipe? Really curious about that one as well
from nest.
@marcelfalliere
SwaggerModule.createDocument()
, take a look at the example above posted by @darioxtx .
For example:
const document = SwaggerModule.createDocument(app, options);
writeFile('swagger/my-service.json', JSON.stringify(document), 'utf8');
You can then serve this static file from any web server you'd like.
For instance, you could create a lightweight http-server
instance that you run by npm run swagger
.
You don't have to use app.listen()
. You could use Swagger UI to present your output .json file.
from nest.
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
from nest.
Related Issues (20)
- Allow readonly arrays as providers, imports, etc. HOT 3
- Validation fails in RPC context for MqttContext HOT 6
- Only the last APP_FILTER providers works HOT 4
- dependency injection does not work. HOT 3
- gRPC Streaming endpoints that throw errors crash the main process HOT 2
- Injectable instances can have references to Request objects and can hold it forewer in request scope
- Middleware consumer have a text error HOT 3
- Extra options are set only to default values when using `registerAsync` HOT 2
- Can we have a template resource for graphql + rest together? HOT 5
- Connection Error in Service during Startup HOT 2
- Wrong type (as in #12264) HOT 3
- Nest CLI generates the wrong package.json file HOT 8
- Watch mode is broken HOT 1
- Hyphens in parameters silently fail HOT 4
- Improve documentation on @Injectable() HOT 2
- Log is not auto-flushed on error during initialization HOT 1
- Middleware not executed when using `exclude` in `setGlobalPrefix` HOT 1
- The use of SetMetadata custom decorators does not take effect HOT 13
- NestJS HttpException class returns success status when status is undefined HOT 4
- NestJs DI `useFactory` ignores property dependencies HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from nest.