Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/simioni/nest-standard-response
Standardized and configurable API responses for NestJS
https://github.com/simioni/nest-standard-response
filtering nestjs node-js nodejs openapi openapi-generator openapi-specification pagination rest rest-api restful-api sorting swagger typescript
Last synced: about 10 hours ago
JSON representation
Standardized and configurable API responses for NestJS
- Host: GitHub
- URL: https://github.com/simioni/nest-standard-response
- Owner: simioni
- License: mit
- Created: 2023-10-14T17:58:20.000Z (12 months ago)
- Default Branch: main
- Last Pushed: 2024-04-02T00:06:22.000Z (6 months ago)
- Last Synced: 2024-09-20T18:30:58.706Z (5 days ago)
- Topics: filtering, nestjs, node-js, nodejs, openapi, openapi-generator, openapi-specification, pagination, rest, rest-api, restful-api, sorting, swagger, typescript
- Language: TypeScript
- Homepage: https://www.npmjs.com/package/nest-standard-response
- Size: 524 KB
- Stars: 7
- Watchers: 2
- Forks: 1
- Open Issues: 3
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Standardized API responses for NestJS
- Metadata-based wrapper to provide customizable and standardized API response objects;
- Built-in handling of pagination, sorting and filtering;
- Allows route handlers to keep returning classes instead of wrapper objects, so they remain fully compatible with interceptors;
- Automatic OpenAPI documentation with proper response schema for all features
- Generation of OpenAPI response examples with proper serialization for each user role
# Getting started
## đ Â Install
```shell
$ npm install nest-standard-response
```## 𮠠Add to your app's ```imports``` array
```app.module.ts```
```ts
import { StandardResponseModule } from 'nest-standard-response';@Module({
imports: [
StandardResponseModule.forRoot(options), // options can be ommited
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
```Check out the options that this module accepts in the [Advanced Configuration](#StandardResponseConfiguration) section.
## đĻ Â All routes are now wrapped
By default, all routes are automatically wrapped in a standard response object:
```ts
// route returns dtos
@get("/books")
listBooks(): BookDto[] {
const books = [
new BookDto({ title: "Dune", year: 1965 }),
new BookDto({ title: "Jaws", year: 1974 }),
new BookDto({ title: "Emma", year: 1815 }),
];
return books;
}
``````ts
// but response is wrapped
{
success: true,
isArray: true, // auto infered
data: [
{ title: "Dune", year: 1965 },
{ title: "Jaws", year: 1974 },
{ title: "Emma", year: 1815 },
]
}
```> To skip wrapping a particular route, just decorate the handler with [@RawResponse()](#RawResponseDecorator).
> It's possible to **invert** this behavior to **not wrap** any route automatically, and only wrap routes annotated with [@StandardResponse()](#StandardResponseDecorator) instead. [Check out how](#StandardResponseConfiguration-interceptAll).
## đĻ Â Wrapping only happens at the end of the NestJS' request pipeline
So interceptors like ```ClassSerializer``` and ```RoleSerializer``` work transparently without any custom logic.
## đĨ Â Add features to your route
Just decorate a route with [@StandardResponse({...options})](#StandardResponseDecorator) and pass in the options you want. Adding features will:
- Automatically prepare a route to receive query parameters for that feature;
- Parse and validate the input of these query parameters, and make them injectable into the handler;
- Add fields to the response object to let the client know the state of these features (and to allow discoverability of defaults when the route is called without any query params);
- Add documentation to Swagger with fully qualified schemas and examples;To access this information during the request, use the [@StandardParam()](#StandardParamDecorator) parameter decorator to inject a params object into your handler. This object contains the parsed query params, all the configuration values you set in the ```@StandardResponse()```, plus methods to manipulate and add data into the response.
```ts
// route
@get("/books")
@StandardResponse({ isPaginated: true })
async listBooks(
@StandardParam() params: StandardParams
): BookDto[] {
const {
books,
count
} = await this.bookService.list({
// already validated values safe to use
limit: params.pagination.limit,
offset: params.pagination.offset,
});
// add extra information into the response
params.setPaginationInfo({ count: count })
return books;
}
``````ts
// response
{
success: true,
isArray: true,
isPaginated: true,
pagination: {
limit: 10,
offset: 0,
defaultLimit: 10,
// đ added in handler
count: 33
},
data: [
{ title: "Dune", year: 1965 },
{ title: "Jaws", year: 1974 },
{ title: "Emma", year: 1815 },
]
}
```
## đ Â Combine features!
Features can be freely combined, or used all at once.
For example, using the features shown bellow, the route could be called like this:
>```/books?limit=8&offset=16&sort=-author,title&filter=author^=Frank;year>=1960;year>=1970```
> Note: This url was NOT url-encoded for readability (but you would need to encode yours)```ts
// route
@get("/books")
@StandardResponse({
// đ declare type to get OpenApi docs
type: [BookDto],
isPaginated: true,
defaultLimit: 12,
maxLimit: 20,
isSorted: true,
sortableFields: ["title", "author"],
isFiltered: true,
filterableFields: ["author", "year"],
})
async listBooks(
@StandardParam() params: StandardParams
): BookDto[] {
const {
books,
count
} = await this.bookService.list({
limit: params.pagination.limit,
offset: params.pagination.offset,
sort: params.sorting.sort,
filter: params.filtering.filter,
});
// đ to see how the 'sort' and 'filter'
// params are parsed, look at the
// SortingInfo and FilteringInfo classes
// in the @StandardParam() section of
// this document// đ add extra information into the response
params.setPaginationInfo({ count: count })
params.setMessage('A full-featured example!')
return books;
}```
```ts
// response
{
success: true,
message: "A full-featured example!",
isArray: true,
isPaginated: true,
isSorted: true,
isFiltered: true,
pagination: {
query: "limit=8&offset=16",
limit: 8,
offset: 16,
defaultLimit: 12,
maxLimit: 20,
count: 33
},
sorting: {
sortableFields: ["title", "author"],
query: "-author,title",
sort: [
{
field: "author",
order: "des"
},
{
field: "title",
order: "asc"
}
]
},
filtering: {
filterableFields: ["author", "year"],
query: "author^=Frank;year>=1960;year>=1970",
filter: {
allOf: [
{ anyOf: [
{
field: 'author',
operation: '^=',
value: "Frank"
},
]},
{ anyOf: [
{
field: 'year',
operation: '>=',
value: 1960
},
]},
{ anyOf: [
{
field: 'year',
operation: '<=',
value: 1970
},
]}
]
}
},
data: [ ... ]
}
```For detailed information on the objects generated by filtering and sorting, as well as a list of all operations available, see the documentation for the [@StandardParam()](#StandardParamDecorator) decorator.
---------------------------------------------------------------------------
# Reference
* [@StandardResponse()](#StandardResponseDecorator) decorator
* [StandardResponseOptions](#StandardResponseOptions)
* [@RawResponse()](#RawResponseDecorator) decorator
* [@StandardParam()](#StandardParamDecorator) parameter decorator
* [Advanced Configuration](#StandardResponseConfiguration)## đ Â @StandardResponse(_options?:_ [_StandardResponseOptions_](#StandardResponseOptions))
A decorator that wraps the return of a route into a standardized API response object (while still allowing the handler to return true DTOs or other model class instances â this makes interceptors like caching, ```ClassSerializer```, or ```RoleSerializer``` work transparently.)
The wrapper allows custom messages to be set in the response, and has optional features to handle common tasks, like **pagination, sorting and filtering**.
It can also optionally apply swagger's documentation, providing the correct combined schema for the DTO and the wrapper including any of its features. If given an array of Roles, it can also build Swagger route response examples for each user role, containing the reponse as it would be serialized for that user group.
``` ts
import { UserDto } from './dto/user.dto';@Controller('users')
export class UsersController {
constructor(
private readonly usersService: UsersService,
) {}@Get('/')
@StandardResponse({ type: [UserDto] })
async findAll(): Promise {
const users = await this.usersService.findAll();
return users // <--- returns an array of UserDtos
}
}// get /api/users
// Response:
{
"success": true,
"isArray": true,
"data": [
Users... // <--- The returned array is delivered inside the data property
]
}
```(TODO image of swagger UI with the response examples dropdown open. Comparing a response for User and Admin, with arrows showcasing the extra fields returned only to admin)
## 𸠠StandardResponseOptions
Option
Type
Description
type
Class
The class that represents the object(s) that will be returned from the route (for example, a Model or a DTO). This option is required to get auto-documentation.
description
string
Used as the desciption field of the response in the OpenAPI docs.
isPaginated
boolean
Mark the route to serve paginated responses, and allow the use of pagination options. This will capture and validatelimit
andoffset
query parameters, and make them available in the handler via@StandardParam
. Also sets up pagination fields in the response object.
isSorted
boolean
Mark the route to serve sorted responses, and allow the use of sorting options. This will capture and validate thesort
query parameter, and make it available in the handler via@StandardParam
. Also sets up sorting fields in the response object.
isFiltered
boolean
Mark the route to serve filtered responses, and allow the use of filtering options. This will capture and validate thefilter
query parameter, parse it into aFilteringQuery
, an and make it available in the handler via@StandardParam
. Also sets up filtering fields in the response object.
defaultLimit
number
(Pagination option) The value to used forlimit
if the query param is missing. (Defaults to 10)
maxLimit
number
(Pagination option) The maximum value accepted by thelimit
query param.
minLimit
number
(Pagination option) The minimum value accepted by thelimit
query param.
sortableFields
string[]
(Sorting option) A list of fields that can used for sorting. If left undefined, all fields will be accepted. An empty array allows no fields.
filterableFields
string[]
(Filtering option) A list of fields that can used for filtering. If left undefined, all fields will be accepted. An empty array allows no fields.
---------------------------------------------------
The default behavior of StandardResponse is to wrap the response from all routes application wide. This keeps the API consistent and predictable. However, if you need to skip this behavior for a particular route, just set the ```@RawResponse()``` decorator:
```ts
@Controller('external-api-integration')
export class ExternalApiIntegrationController {
@Get('/')
@RawResponse() // <--- will skip wrapping
async findAll(): Promise {
return customObject;
}
}
```If you're adding StandardResponse into an existing app, it might be useful to invert this behavior to create a gradual transition path. To do this, set the ```interceptAll``` option to ```false``` when importing the ```StandardResponseModule``` in your application. This way, routes will only be wrapped if they have explicitly set the ```@StandardResponse()``` decorator. See more information in the "Configuring" section bellow.
---------------------------------------------------
A parameter decorator used to inject a ```StandardParams``` object in the route handler.
This object allows access to:
* All options set in ```@StandardResponse()```;
* Information captured from query parameters, parsed and validated;
* Methods to include and modify fields in the response object;
``` ts
import { UserDto } from './dto/user.dto';@Controller('users')
export class UsersController {
constructor(
private readonly usersService: UsersService,
) {}@Get('/')
@StandardResponse({
type: [UserDto],
isPaginated: true,
maxLimit: 24,
defaultLimit 12,
})
async findAll(
@StandardParam() params: StandardParams // <--- inject into handler
): Promise {
const [users, count] = await this.usersService.findAll({
limit: params.pagination.limit,
offset: params.pagination.offset,
});
params.setPaginationInfo({ count: 348 }) // <--- set additional info
return users;
}
}// get /api/users?limit=15&offset=30
// Response:
{
"success": true,
"isArray": true,
"isPaginated": true,
"pagination: {
count: 348, // <--- added inside the handler
limit: 15, // <--- from query
offset: 30,
maxLimit: 24, // <--- from decorator options
defaultLimit: 12,
}
"data": [
Users...
]
}
```
The params object injected with @StandardParam() contains these keys:
Key
Type
Description
pagination
PaginationInfo
Only available when the responseisPaginated
option istrue
.
sorting
SortingInfo
Only available when the responseisSorted
option istrue
.
filtering
FilteringInfo
Only available when the responseisFiltered
option istrue
.
setPaginationInfo()
(info: {}) => void
Allows modifying the pagination metadata inside the route handler to add extra information or to reflect some dynamic condition. For example, to add a paginationcount
. The object passed to this method will be merged with the current information, so partial updates are OK.
setSortingInfo()
(info: {}) => void
Allows modifying the sorting metadata inside the route handler.
setFilteringInfo()
(info: {}) => void
Allows modifying the filtering metadata inside the route handler.
setMessage()
(message: string) => void
Allows setting a custom message in the response object.
## 𸠠PaginationInfo
Property
Type
Description
query?
string
The original string from the request for thelimit
andoffset
query params. [ReadOnly]
limit?
number
How many items to send. This is the same as thelimit
query param, but parsed and validated.
offset?
number
How many items to skip. This is the same as theoffset
query param, but parsed and validated.
count?
number
The total count of items that are being paginated. This value needs to be set inside the handler using thesetPaginationInfo()
method.
maxLimit?
number
The maximum value accepted by thelimit
query param. [ReadOnly] (From the options set in@StandardResponse()
).
minLimit?
number
The minimum value accepted by thelimit
query param. [ReadOnly] (From the options set in@StandardResponse()
).
defaultLimit?
number
The default number of items to send if no querylimit
is provided. [ReadOnly] (From the options set in@StandardResponse()
).
## 𸠠SortingInfo
Property
Type
Description
query?
string
The original string from the request for thesort
query param.
sortableFields?
string[]
A list of all the fields that can used for sorting. [ReadOnly] (From the options set in@StandardResponse()
).
sort?
SortingOperation[]
An array ofSortingOperation
objects parsed from the query.
Â
SortingOperation
field
string
The name of the field being sorted.
order
'asc' | 'des'
Order of the sorting operation. These strings are available in an enum for static typing:SortingOrder.ASC
andSortingOrder.DES
.
## 𸠠FilteringInfo
Property
Type
Description
query?
string
The original string from the request for thefilter
query param.
filterableFields?
string[]
A list of all the fields that can used for filtering. [ReadOnly] (From the options set in@StandardResponse()
).
filter?
{ allOf: FilteringQueryGroup[] }
Filter is an object parsed from the query containing a single property: allOf. This is an array ofFilteringQueryGroup
objects. All of these filter groups should be combined using an AND operation.
Â
FilteringQueryGroup
anyOf
FilteringQueryOperation[]
An array ofFilteringQueryOperation
objects. These filters should be combined using an OR operation.
Â
FilteringQueryOperation
field
string
Name of the field to filter on.
operation
string
The comparison operation to perform. Possible operators are bellow.
value
string
Value used for the comparison.
Operation
Description
URL Encoded Form
Example
==
Equals
%3D%3D
.
!=
Not Equals
!%3D
.
<=
Less than or equal to
%3C%3D
.
<
Less than
%3C
.
>=
Greater than or equal to
%3E%3D
.
>
Greater than
%3E
.
=@
Contains
%3D@
.
!@
Does not contain
!@
.
=^
Starts with
%3D%5E
.
=$
Ends with
%3D%24
.
These rules are similar to other APIs like Google Analytics or Matomo Analytics.## 𸠠Building the search query
When building a query, all **AND** operations should be separated by a **semicolon (;)**, and all **OR** operations should be separed by a **comma (,)**. For example:
This query will filter all books available for lending, which were first published in France OR Italy, between 1970 AND 1999, whose author starts with Vittorio OR ends with Alatri:
```
available==true;country==France,country==Italy;year>=1970;year<=1999;author=^Vittorio,author=$Alatri
```The resulting parsed object from this query will be:
```ts
{ allOf: [
{ anyOf: [
{ field: 'available', operation: '==', value: true },
]},
{ anyOf: [
{ field: 'country', operation: '==', value: 'France' },
{ field: 'country', operation: '==', value: 'Italy' },
]},
{ anyOf: [
{ field: 'year', operation: '>=', value: 1970 },
]},
{ anyOf: [
{ field: 'year', operation: '<=', value: 1999 },
]},
{ anyOf: [
{ field: 'author', operation: '=^', value: 'Vittorio' },
{ field: 'author', operation: '=$', value: 'Alatri' },
]},
]}
```---------------------------------------------------
# đ Â Advanced configuration
## â validateResponse
Allows you to provide a validation function to stop the return of a route if certain conditions are met.
For example: this can abort a request if a route tries to return â instead a DTO â a raw DB document or some other object that may leak information not intended to be exposed.
This function should return ```false``` to abort the request.
```ts
@Module({
imports: [
StandardResponseModule.forRoot({
validateResponse: (data) => {
if (isMongooseObject(data)) return false;
return true;
},
}),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
```
Setting ```interceptAll``` to ```false``` will invert the default behavior of wrapping all routes by default, and will instead only wrap routes decorated with ```@StandardResponse()```.
```ts
@Module({
imports: [
StandardResponseModule.forRoot({
interceptAll: false
}),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
```
---------------------------------------------------
## đ Â TODO Milestones
- Allow setting any custom field in the repsonse object by exposing a method in the StandardParam: ```setExtra(field, value)```;
đ âī¸ đšī¸ đĄ đ đŠ âī¸ 𧹠đŽ đ đī¸ đ đĒ âī¸ âī¸ đŠ
đĻ đˇī¸ đŽ
đ đ§ đļ đ¸