what is the proper way to create a swagger web service in TypeScript - node.js

I am part of a project written in TypeScipt and I am trying to add TypeScript Web Server which will be compatible with Swagger.
What is the most basic strategy to implement it, considering easy maintainability.
For Typescript I have notice that exists 'Typson' library for generating a JSON Model from TypeScript Interface.
For Swagger, I have tried using 'swagger-node-restify' library, since it supports adding JSON models to swagger.
However, I encounter some problems:
Typson doesn't support typeScript syntax of Import -
(import {Server} from "restify")
I tried to implement the 'swagger-node-restify' example (Pet Example), however the RESPONSE of the localhost:8080/api-docs.json GET Request is missing all the SPEC data of the API.
{"apiVersion":"0.1","swaggerVersion":"1.1","basePath":"http://localhost:8080","apis":[{"path":"/api-docs.{format}/pet","description":"none"}]}

I suggest to describe a Swagger compliant API using yaml or json and to generate the server from that.
swagger-server can build APIs on top of express in real time (no source code generation).
There are JavaScript code generators :
Call the swagger-codegen client with -l nodejs-server
swagger-node is a great alternative but seems hard to integrate with TypeScript

Yes, you can easily generate Swagger and OpenAPI documents from your TypeScript types by using tsoa. The readme contains all of the setup information that you would need to start using it. It's compatible with express, hapi, koa, and more (via the ability to add your own template for your preferred server type):
https://github.com/lukeautry/tsoa
The advantages that tsoa has over other libraries is:
it both generates the swagger/OpenAPI document and it also validates the types at runtime
(Full Transparency: I am one of the maintainers of tsoa. But I was first a consumer of tsoa and I find it to be a great product... that's why I asked to help maintain it! :) )

Related

swagger - extract parameter info from express-validation

I'm new to node, swagger etc.
I'm working on a node.js app, I added some endpoints and using express-validation package I configured validators for my end points.
I now started using also swagger-autogen to generate swagger doc, but I can't find a way to make swagger use the validators in order to provide more data/limitations of the endpoints' parameters.
Is there a way to achieve something like that?
Thanks

AsyncAPI - How to distribute definition over different files

I am thinking of using AsyncAPI in my project for documenting the RabbitMQ messaging system.
What I need to do is, rather than creating a single yaml/json file for all the messages in the application, I want to create the AsyncAPI definition for each message in its own file, very much like its done in Swagger.
I am using Swagger 2.0, on a node express server for the REST API definitions. For the definition of the APIs, I write comments on each API with the #swagger decorator for Swagger to pick up the documentation. For example:
/**
* #swagger
* /user/register:
* post:
* description: Register a new user
...
...
*/
I also have a common definition in a routes.js file, where I define all the reusables.
Such definitions sit on the top of each API end point file. Swagger, collects all these documentations distributed over various files, and creates a single documentation for all the APIs in the application.
I was wondering if something similar can be done in AsyncAPI and if yes, how do I achieve that.
Would really appreciate your response on this.
Thanks,
Rachit
What I need to do is, rather than creating a single yaml/json file for all the messages in the application, I want to create the AsyncAPI definition for each message in its own file, very much like its done in Swagger.
Split definition of schema objects across several files is possible in AsyncAPI exactly in the same way like in OpenAPI
I am using Swagger 2.0, on a node express server for the REST API definitions. For the definition of the APIs, I write comments on each API with the #swagger decorator for Swagger to pick up the documentation. For example:
Up to now there is no code-first tool to generate AsyncAPI from the JS source code

Generate openApi DTO's with NestJS without a Controller

I am writing a NestJS service that provides a REST API and it publishes some messages to NATS. We are using the NestJS support to generate OpenAPI docs, and from the OpenAPI docs we generate an SDK that we import into our clients. This all works great, but only the REST API of our code is in the SDK.
What we'd like to also do is to have NestJS include the DTO's for the content for the messages we publish to NATS. Then our SDK will also include interfaces for these DTO's, and then our clients can cast the message content to the correct interface (based on the message subject). This way, the publisher of an event defines the content of the event, and users of it don't have to replicate the interface, yet they get strongly-typed code.
I've tried adding the #Api decorators to the DTO, but it appears that unless the DTO is used in the definition of an #Controller, it is not included in the resultant openApi docs.
I was hoping for a way to decorate a "random" DTO in my code so it will then be included in the swagger docs, and in-turn included in a generated SDK. Is something like that possible?
you can also pass extraModels array as a part of SwaggerDocumentOptions
SwaggerModule.createDocument(app, config, {
extraModels: [.......]
});
https://github.com/nestjs/swagger/issues/241

Generate javascript client from Servicestack api metadata/swagger

is there any way to auto-generate ServiceStack javascript (no typescript) client based on metadata/Swagger? It would be good to integrate that somehow with webpack.
I am not sure is it possible to do this with swagger-js-codegen (This package generates a nodejs or angularjs class from a swagger specification file).
Actually swagger plugin doesn't share service to access swagger.json to get complete schema (the schema is splited). Is there any workaround to use swagger codegen for javascript?
By accessing http://localhost:12116/resources you can get
{"swaggerVersion":"1.2","apis":[{"path":"/resource/assignroles"},{"path":"/resource/auth"},{"path":"/resource/authenticate"},{"path":"/resource/criteria"},{"path":"/resource/import"},{"path":"/resource/tenders"},{"path":"/resource/unassignroles"}],"apiVersion":"1.0","basePath":"http://localhost:12116","info":{"title":"App"}}
and using http://localhost:12116/resource/import
{"swaggerVersion":"1.2","apiVersion":"1.0","basePath":"http://localhost:12116","resourcePath":"/import","apis":[{"path":"/import/stats","operations":[{"method":"GET","nickname":"BrowseImportStats","parameters":[],"errorResponses":[]}]},{"path":"/import/tenders/changes/apply","operations":[{"method":"GET","nickname":"ApplyChanges","parameters":[],"errorResponses":[]},{"method":"POST","nickname":"ApplyChanges","parameters":[{"paramType":"body","name":"body","required":false,"allowMultiple":false,"type":"ApplyChanges"}],"errorResponses":[]},{"method":"PUT","nickname":"ApplyChanges","parameters":[{"paramType":"body","name":"body","required":false,"allowMultiple":false,"type":"ApplyChanges"}],"errorResponses":[]},{"method":"DELETE","nickname":"ApplyChanges","parameters":[],"errorResponses":[]}]},{"path":"/import/tenders/sync","description":"summary","operations":[{"method":"GET","summary":"summary","nickname":"ImportTenders","parameters":[],"errorResponses":[]}]}],"models":{"ImportTenders":{"id":"ImportTenders","properties":{}},"ApplyChanges":{"id":"ApplyChanges","properties":{}},"BrowseImportStats":{"id":"BrowseImportStats","description":"BrowseImportStats","properties":{}}}}
update 2016-11-26
I was able to generate documentation
C:\git\testapp>java -jar swagger-codegen-cli-2.2.1.jar generate -i http
://localhost:12116/resources -l javascript -o ./node_modules/testapp_api --additi
onal-properties emitJSDoc=false,usePromises=true
Given that you've the OpenAPI/Swagger spec, you can leverage Swagger Codegen to generate not only JS API clients but API clients in other langauges (C#, Ruby, PHP, Python, etc), server stubs (Spring, NodeJS, etc) and API documentation.
Here is a good starting point: https://github.com/swagger-api/swagger-codegen#getting-started
(If you do not want to install anything, you can also generate code online: https://github.com/swagger-api/swagger-codegen#online-generators)

How should I use Swagger with Hapi?

I have a working ordinary Hapi application that I'm planning to migrate to Swagger. I installed swagger-node using the official instructions, and chose Hapi when executing 'swagger project create'. However, I'm now confused because there seem to be several libraries for integrating swagger-node and hapi:
hapi-swagger: the most popular one
hapi-swaggered: somewhat popular
swagger-hapi: unpopular and not that active but used by the official Swagger Node.js library (i.e. swagger-node) as default for Hapi projects
I though swagger-hapi was the "official" approach, until I tried to find information on how do various configurations on Hapi routes (e.g. authorization, scoping, etc.). It seems also that the approaches are fundamentally different, swagger-hapi taking Swagger definition as input and generating the routes automatically, whereas hapi-swagger and hapi-swaggered seem to have similar approach with each other by only generating Swagger API documentation from plain old Hapi route definitions.
Considering the amount of contributors and the number of downloads, hapi-swagger seems to be the way to go, but I'm unsure on how to proceed. Is there an "official" Swagger way to set up Hapi, and if there is, how do I set up authentication (preferably by using hapi-auth-jwt2, or other similar JWT solution) and authorization?
EDIT: I also found swaggerize-hapi, which seems to be maintained by PayPal's open source kraken.js team, which indicates that it might have some kind of corporate backing (always a good thing). swaggerize-hapi seems to be very similar to hapi-swagger, although the latter seems to provide more out-of-the-box functionality (mainly Swagger Editor).
Edit: Point 3. from your question and understanding what swagger-hapi actually does is very important. It does not directly serves the swagger-ui html. It is not intended to, but it is enabling the whole swagger idea (which the other projects in points 1. and 2. are actually a bit reversing). Please see below.
It turns out that when you are using swagger-node and swagger-hapi you do not need all the rest of the packages you mentioned, except for using swagger-ui directly (which is used by all the others anyways - they are wrapping it in their dependencies)
I want to share my understanding so far in this hapi/swagger puzzle, hope that these 8 hours that I spent can help others as well.
Libraries like hapi-swaggered, hapi-swaggered-ui, also hapi-swagger - All of them follow the same approach - that might be described like that:
You document your API while you are defining your routes
They are somewhat sitting aside from the main idea of swagger-node and the boilerplate hello_world project created with swagger-cli, which you mentioned that you use.
While swagger-node and swagger-hapi (NOTE that its different from hapi-swagger) are saying:
You define all your API documentation and routes **in a single centralized place - swagger.yaml**
and then you just focus on writing controller logic. The boilerplate project provided with swagger-cli is already exposing this centralized place swagger.yaml as json thru the /swagger endpoint.
Now, because the swagger-ui project which all the above packages are making use of for showing the UI, is just a bunch of static html - in order to use it, you have two options:
1) to self host this static html from within your app
2) to host it on a separate web app or even load the index.html directly from file system.
In both cases you just need to feed the swagger-ui with your swagger json - which as said above is already exposed by the /swagger endpoint.
The only caveat if you chose option 2) is that you need to enable cors for that end point which happened to be very easy. Just change your default.yaml, to also make use of the cors bagpipe. Please see this thread for how to do this.
As #Kitanotori said above, I also don't see the point of documenting the code programmatically. The idea of just describing everything in one place and making both the code and the documentation engine to understand it, is great.
We have used Inert, Vision, hapi-swagger.
server.ts
import * as Inert from '#hapi/inert';
import * as Vision from '#hapi/vision';
import Swagger from './plugins/swagger';
...
...
// hapi server setup
...
const plugins: any[] = [Inert, Vision, Swagger];
await server.register(plugins);
...
// other setup
./plugins/swagger
import * as HapiSwagger from 'hapi-swagger';
import * as Package from '../../package.json';
const swaggerOptions: HapiSwagger.RegisterOptions = {
info: {
title: 'Some title',
version: Package.version
}
};
export default {
plugin: HapiSwagger,
options: swaggerOptions
};
We are using Inert, Vision and hapi-swagger to build and host swagger documentation.
We load those plugins in exactly this order, do not configure Inert or Vision and only set basic properties like title in the hapi-swagger config.

Resources