Generate openApi DTO's with NestJS without a Controller - node.js

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

Related

OpenAPI Generator issue with Destination service API specification

I want to get all destinations on subaccount and instance level. In SAP API business Hub, I found the API information and "SAP Cloud SDK" tab to generate code by OpenAPI generator.
https://api.sap.com/api/SAP_CP_CF_Connectivity_Destination/overview
I downloaded the API specification and added dependencies into Cloud SDK for Java project. The code is generated successfully with some errors (unknown models)in generated api classes.
For example in DestinationsOnSubaccountLevelApi.class, model OneOfDestinationNameOnly is imported and used in method but it is not generated in model package.
I looked into API specification and found that there were two types of response entity. That is the reason why the code could not be generated properly. I can modify the API specification to make it work but it should not be the long term solution. Is there any other way to fix this issue?
Unfortunately the SAP Cloud SDK Generator for Open API services is not yet able to understand oneOf relationship that is modeled in the specification.
As an alternative, would you consider using the DestinationAccessor API for resolving single destinations?
You can also directly instantiate an ScpCfDestinationLoader, which allows for querying all destinations:
ScpCfDestinationLoader loader = new ScpCfDestinationLoader();
DestinationOptions options = DestinationOptions
.builder()
.augmentBuilder(ScpCfDestinationOptionsAugmenter.augmenter().retrievalStrategy(ScpCfDestinationRetrievalStrategy.ALWAYS_SUBSCRIBER))
.build();
Try<Iterable<ScpCfDestination>> destinations = loader.tryGetAllDestinations(options);
Similar to the default behavior of DestinationAccessor API, in the code above only the subscriber account will be considered. Other options are:
ScpCfDestinationRetrievalStrategy.ALWAYS_SUBSCRIBER
ScpCfDestinationRetrievalStrategy.ALWAYS_PROVIDER
ScpCfDestinationRetrievalStrategy.SUBSCRIBER_THEN_PROVIDER

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

Independent NPM library that validates request based on swagger file

We are building APIs using Swagger, AWS API gateway and Lambda functions with NodeJS. The API gateway will do the request validation, however as per the design, the lambda functions need to re-validate the request object as an API Gateway Proxy Request Event. This makes sense as in theory we can reuse the lambda functions by invoking them via other event source (e.g. SNS).
Therefore we need an NodeJS tool which can validate the request (not only body but also params, etc) based on the swagger spec - exactly what the swagger-tools and a few other tools (e.g. swagger-request-validator) are doing, but not as a middleware.
I did some search but could not find one, also looked into swagger-tools source code, reckon its validation component was written in the way that cannot be easily used separately.
Any suggestion is welcome. Thanks in advance.
You can use swagger-model-validator.
var Validator = require('swagger-model-validator');
var swaggerFile = require("./swagger.json");
const validator = new Validator(swaggerFile);
console.log(validator.validate({
name: 'meg'
}, swaggerFile.definitions.Pet, swaggerFile.definitions, true).GetErrorMessages())
This outputs:
[ 'photoUrls is a required field' ]
validator.validate returns an object, so you can also check if the returned object contains anything under the errors attribute. It should be as simple as
if (validator.validate({
name: 'meg'
}, swaggerFile.definitions.Pet, swaggerFile.definitions, true).errors) {
// do something with error
}
I have used Swagger's sample JSON for this answer.

Foxx/ArangoDB: Can you create a response that adhere to JSON API specification?

I am currently writing some micro services with Foxx to be consumed by Ember.js. Ember data plays very nicely with JSON API (http://jsonapi.org) responses. So I tried to serialize the Foxx responses with the json-api-serializer (https://www.npmjs.com/package/json-api-serializer) - but with no luck. I only found the forClient method, but this only allows me to operate on the JSON representation of single objects, not the whole response. So my question: Is it possible to implement JSON API with Foxx/ArangoDB?
You can return arbitrary responses from Foxx routes, so it's entirely possible to generate JSON responses that conform to JSON API.
However there's no built-in way to do this automatically.
I don't see anything in json-api-serializer that shouldn't work in Foxx, so I'm not sure what problems you are encountering. You should be able to simply return the output object with res.json(outputFromSerializer) and set the content type with res.set('content-type', 'application/vnd.api+json').
If everything else fails you can just write your own helper functions to generate the boilerplate and metadata JSON API expects.

what is the proper way to create a swagger web service in TypeScript

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! :) )

Resources