@tsed/openapi-utils 8.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/esm/decorators/docs.js +14 -0
- package/lib/esm/decorators/docs.js.map +1 -0
- package/lib/esm/index.js +15 -0
- package/lib/esm/index.js.map +1 -0
- package/lib/esm/interfaces/OpenApiSettings.js +2 -0
- package/lib/esm/interfaces/OpenApiSettings.js.map +1 -0
- package/lib/esm/middlewares/cssMiddleware.js +20 -0
- package/lib/esm/middlewares/cssMiddleware.js.map +1 -0
- package/lib/esm/middlewares/jsMiddleware.js +15 -0
- package/lib/esm/middlewares/jsMiddleware.js.map +1 -0
- package/lib/esm/middlewares/openApiMiddleware.js +13 -0
- package/lib/esm/middlewares/openApiMiddleware.js.map +1 -0
- package/lib/esm/middlewares/redirectMiddleware.js +14 -0
- package/lib/esm/middlewares/redirectMiddleware.js.map +1 -0
- package/lib/esm/services/OpenAPIBaseModule.js +67 -0
- package/lib/esm/services/OpenAPIBaseModule.js.map +1 -0
- package/lib/esm/services/OpenAPIService.js +46 -0
- package/lib/esm/services/OpenAPIService.js.map +1 -0
- package/lib/esm/utils/includeRoute.js +16 -0
- package/lib/esm/utils/includeRoute.js.map +1 -0
- package/lib/esm/utils/matchPath.js +5 -0
- package/lib/esm/utils/matchPath.js.map +1 -0
- package/lib/esm/utils/readSpec.js +14 -0
- package/lib/esm/utils/readSpec.js.map +1 -0
- package/lib/types/decorators/docs.d.ts +10 -0
- package/lib/types/index.d.ts +14 -0
- package/lib/types/interfaces/OpenApiSettings.d.ts +96 -0
- package/lib/types/middlewares/cssMiddleware.d.ts +5 -0
- package/lib/types/middlewares/jsMiddleware.d.ts +5 -0
- package/lib/types/middlewares/openApiMiddleware.d.ts +5 -0
- package/lib/types/middlewares/redirectMiddleware.d.ts +5 -0
- package/lib/types/services/OpenAPIBaseModule.d.ts +18 -0
- package/lib/types/services/OpenAPIService.d.ts +15 -0
- package/lib/types/utils/includeRoute.d.ts +3 -0
- package/lib/types/utils/matchPath.d.ts +1 -0
- package/lib/types/utils/readSpec.d.ts +1 -0
- package/package.json +59 -0
- package/readme.md +257 -0
- package/src/decorators/docs.ts +14 -0
- package/src/index.ts +14 -0
- package/src/interfaces/OpenApiSettings.ts +98 -0
- package/src/middlewares/cssMiddleware.spec.ts +25 -0
- package/src/middlewares/cssMiddleware.ts +22 -0
- package/src/middlewares/jsMiddleware.spec.ts +25 -0
- package/src/middlewares/jsMiddleware.ts +16 -0
- package/src/middlewares/openApiMiddleware.spec.ts +31 -0
- package/src/middlewares/openApiMiddleware.ts +16 -0
- package/src/middlewares/redirectMiddleware.spec.ts +32 -0
- package/src/middlewares/redirectMiddleware.ts +15 -0
- package/src/services/OpenAPIBaseModule.ts +91 -0
- package/src/services/OpenAPIService.spec.ts +35 -0
- package/src/services/OpenAPIService.ts +65 -0
- package/src/services/__snapshots__/OpenAPIService.spec.ts.snap +11 -0
- package/src/services/__snapshots__/SwaggerService.spec.ts.snap +11 -0
- package/src/utils/includeRoute.spec.ts +111 -0
- package/src/utils/includeRoute.ts +22 -0
- package/src/utils/matchPath.ts +5 -0
- package/src/utils/readSpec.ts +15 -0
- package/vitest.config.mts +21 -0
package/readme.md
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
<p style="text-align: center" align="center">
|
|
2
|
+
<a href="https://tsed.dev" target="_blank"><img src="https://tsed.devtsed-og.png" width="200" alt="Ts.ED logo"/></a>
|
|
3
|
+
</p>
|
|
4
|
+
|
|
5
|
+
<div align="center">
|
|
6
|
+
<h1>Swagger</h1>
|
|
7
|
+
|
|
8
|
+
[](https://github.com/tsedio/tsed/actions?query=workflow%3A%22Build+%26+Release%22)
|
|
9
|
+
[](https://github.com/tsedio/tsed/blob/master/CONTRIBUTING.md)
|
|
10
|
+
[](https://badge.fury.io/js/%40tsed%2Fcommon)
|
|
11
|
+
[](https://github.com/semantic-release/semantic-release)
|
|
12
|
+
[](https://github.com/prettier/prettier)
|
|
13
|
+
[](https://github.com/sponsors/romakita)
|
|
14
|
+
[](https://opencollective.com/tsed)
|
|
15
|
+
|
|
16
|
+
</div>
|
|
17
|
+
|
|
18
|
+
<div align="center">
|
|
19
|
+
<a href="https://tsed.dev">Website</a>
|
|
20
|
+
<span> • </span>
|
|
21
|
+
<a href="https://tsed.dev/getting-started/">Getting started</a>
|
|
22
|
+
<span> • </span>
|
|
23
|
+
<a href="https://slack.tsed.io">Slack</a>
|
|
24
|
+
<span> • </span>
|
|
25
|
+
<a href="https://twitter.com/TsED_io">Twitter</a>
|
|
26
|
+
</div>
|
|
27
|
+
|
|
28
|
+
<hr />
|
|
29
|
+
|
|
30
|
+
A package of Ts.ED framework. See website: https://tsed.io/tutorials/swagger
|
|
31
|
+
|
|
32
|
+
## Installation
|
|
33
|
+
|
|
34
|
+
Before using the Swagger, we have to install the [swagger-ui-express](https://www.npmjs.com/package/swagger-ui-express) module.
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
npm install --save @tsed/swagger
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Then add the following configuration in your Server:
|
|
41
|
+
|
|
42
|
+
```typescript
|
|
43
|
+
import {Configuration} from "@tsed/di";
|
|
44
|
+
import "@tsed/swagger"; // import swagger Ts.ED module
|
|
45
|
+
import {resolve} from "path";
|
|
46
|
+
|
|
47
|
+
@Configuration({
|
|
48
|
+
swagger: [
|
|
49
|
+
{
|
|
50
|
+
path: "/v2/docs",
|
|
51
|
+
specVersion: "2.0"
|
|
52
|
+
},
|
|
53
|
+
{
|
|
54
|
+
path: "/v3/docs",
|
|
55
|
+
specVersion: "3.0.1"
|
|
56
|
+
}
|
|
57
|
+
]
|
|
58
|
+
})
|
|
59
|
+
export class Server {}
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
> The path option for swagger will be used to expose the documentation (ex: http://localhost:8000/api-docs).
|
|
63
|
+
|
|
64
|
+
Normally, Swagger-ui is ready. You can start your server and check if it work fine.
|
|
65
|
+
|
|
66
|
+
> Note: Ts.ED will print the swagger url in the console.
|
|
67
|
+
|
|
68
|
+
### Swagger options
|
|
69
|
+
|
|
70
|
+
Some options is available to configure Swagger-ui, Ts.ED and the default spec information.
|
|
71
|
+
|
|
72
|
+
| Key | Example | Description |
|
|
73
|
+
| -------------------- | ------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
|
|
74
|
+
| path | `/api-doc` | The url subpath to access to the documentation. |
|
|
75
|
+
| specVersion | `2.0`, `3.0.1` | The spec version. |
|
|
76
|
+
| doc | `hidden-doc` | The documentation key used by `@Docs` decorator to create several swagger documentations. |
|
|
77
|
+
| cssPath | `${rootDir}/spec/style.css` | The path to the CSS file. |
|
|
78
|
+
| jsPath | `${rootDir}/spec/main.js` | The path to the JS file. |
|
|
79
|
+
| showExplorer | `true` | Display the search field in the navbar. |
|
|
80
|
+
| spec | `{swagger: "2.0"}` | The default information spec. |
|
|
81
|
+
| specPath | `${rootDir}/spec/swagger.base.json` | Load the base spec documentation from the specified path. |
|
|
82
|
+
| outFile | `${rootDir}/spec/swagger.json` | Write the `swagger.json` spec documentation on the specified path. |
|
|
83
|
+
| hidden | `true` | Hide the documentation in the dropdown explorer list. |
|
|
84
|
+
| options | Swagger-UI options | SwaggerUI options. See (https://github.com/swagger-api/swagger-ui/blob/HEAD/docs/usage/configuration.md) |
|
|
85
|
+
| operationIdFormatter | `(name: string, propertyKey: string, path: string) => string` | A function to generate the operationId. |
|
|
86
|
+
| operationIdPattern | `%c_%m` | A pattern to generate the operationId. Format of operationId field (%c: class name, %m: method name). |
|
|
87
|
+
|
|
88
|
+
### Multi documentations
|
|
89
|
+
|
|
90
|
+
It also possible to create several swagger documentations with `doc` option:
|
|
91
|
+
|
|
92
|
+
```typescript
|
|
93
|
+
import {Configuration} from "@tsed/di";
|
|
94
|
+
import "@tsed/swagger"; // import swagger Ts.ED module
|
|
95
|
+
|
|
96
|
+
@Configuration({
|
|
97
|
+
swagger: [
|
|
98
|
+
{
|
|
99
|
+
path: "/api-docs-v1",
|
|
100
|
+
doc: "api-v1"
|
|
101
|
+
},
|
|
102
|
+
{
|
|
103
|
+
path: "/api-docs-v2",
|
|
104
|
+
doc: "api-v2"
|
|
105
|
+
}
|
|
106
|
+
]
|
|
107
|
+
})
|
|
108
|
+
export class Server {}
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
Then use `@Docs` decorators on your controllers to specify where the controllers should be displayed.
|
|
112
|
+
|
|
113
|
+
```typescript
|
|
114
|
+
import {Controller} from "@tsed/di";
|
|
115
|
+
import {Docs} from "@tsed/swagger";
|
|
116
|
+
|
|
117
|
+
@Controller("/calendars")
|
|
118
|
+
@Docs("api-v2") // display this controllers only for api-docs-v2
|
|
119
|
+
export class CalendarCtrlV2 {}
|
|
120
|
+
// OR
|
|
121
|
+
@Controller("/calendars")
|
|
122
|
+
@Docs("api-v2", "api-v1") // display this controllers for api-docs-v2 and api-docs-v1
|
|
123
|
+
export class CalendarCtrl {}
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
## Examples
|
|
127
|
+
|
|
128
|
+
#### Model documentation
|
|
129
|
+
|
|
130
|
+
One of the feature of Ts.ED is the model definition to serialize or deserialize a
|
|
131
|
+
JSON Object (see [converters section](https://tsed.devdocs/components/converters.html)).
|
|
132
|
+
|
|
133
|
+
This model can used on a method controller along with [@BodyParams](https://tsed.devapi/common/filters/decorators/BodyParams.html) or other decorators.
|
|
134
|
+
|
|
135
|
+
```typescript
|
|
136
|
+
import {JsonProperty, Title, Description, Example} from "@tsed/schema";
|
|
137
|
+
|
|
138
|
+
export class CalendarModel {
|
|
139
|
+
@Title("iD")
|
|
140
|
+
@Description("Description of calendar model id")
|
|
141
|
+
@Example("Example value")
|
|
142
|
+
@JsonProperty()
|
|
143
|
+
public id: string;
|
|
144
|
+
|
|
145
|
+
@JsonProperty()
|
|
146
|
+
public name: string;
|
|
147
|
+
}
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
#### Endpoint documentation
|
|
151
|
+
|
|
152
|
+
```typescript
|
|
153
|
+
import {Controller} from "@tsed/di";
|
|
154
|
+
import {BodyParams, QueryParams} from "@tsed/platform-params";
|
|
155
|
+
import {Get, Post, Returns, ReturnsArray, Description, Summary, Deprecated, Security} from "@tsed/schema";
|
|
156
|
+
import {CalendarModel} from "../models/CalendarModel.js";
|
|
157
|
+
|
|
158
|
+
@Controller("/calendars")
|
|
159
|
+
export class Calendar {
|
|
160
|
+
@Get("/:id")
|
|
161
|
+
@Summary("Summary of this route")
|
|
162
|
+
@Description("Description of this route")
|
|
163
|
+
@Returns(CalendarModel)
|
|
164
|
+
@Returns(404, {description: "Not found"})
|
|
165
|
+
async getCalendar(@QueryParams("id") id: string): Promise<CalendarModel> {
|
|
166
|
+
//...
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
@Get("/v0/:id")
|
|
170
|
+
@Deprecated()
|
|
171
|
+
@Description("Deprecated route, use /rest/calendars/:id instead of.")
|
|
172
|
+
@Returns(CalendarModel)
|
|
173
|
+
@Returns(404, {description: "Not found"})
|
|
174
|
+
getCalendarDeprecated(@QueryParams("id") id: string): Promise<CalendarModel> {
|
|
175
|
+
//...
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
@Get("/")
|
|
179
|
+
@Description("Description of this route")
|
|
180
|
+
@ReturnsArray(CalendarModel)
|
|
181
|
+
getCalendars(): Promise<CalendarModel[]> {
|
|
182
|
+
// ...
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
@Post("/")
|
|
186
|
+
@Security("calendar_auth", "write:calendar", "read:calendar")
|
|
187
|
+
@Returns(CalendarModel)
|
|
188
|
+
async createCalendar(@BodyParams() body: any): Promise<CalendarModel> {
|
|
189
|
+
//...
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
::: warninig
|
|
195
|
+
To update the swagger.json you need to reload the server before.
|
|
196
|
+
:::
|
|
197
|
+
|
|
198
|
+
## Import Javascript
|
|
199
|
+
|
|
200
|
+
It possible to import a Javascript in the Swagger-ui documentation. This script let you customize the swagger-ui instance.
|
|
201
|
+
|
|
202
|
+
```typescript
|
|
203
|
+
import {Configuration} from "@tsed/di";
|
|
204
|
+
import "@tsed/swagger"; // import swagger Ts.ED module
|
|
205
|
+
|
|
206
|
+
@Configuration({
|
|
207
|
+
swagger: [
|
|
208
|
+
{
|
|
209
|
+
path: "/api-docs",
|
|
210
|
+
jsPath: "/spec/main.js"
|
|
211
|
+
}
|
|
212
|
+
]
|
|
213
|
+
})
|
|
214
|
+
export class Server {}
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
In your JavaScript file, you can handle Swagger-ui configuration and the instance:
|
|
218
|
+
|
|
219
|
+
```javascript
|
|
220
|
+
console.log(SwaggerUIBuilder.config); //Swagger-ui config
|
|
221
|
+
|
|
222
|
+
document.addEventListener("swagger.init", (evt) => {
|
|
223
|
+
console.log(SwaggerUIBuilder.ui); //Swagger-ui instance
|
|
224
|
+
});
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
## Documentation
|
|
228
|
+
|
|
229
|
+
See our documentation https://tsed.dev#/api/index
|
|
230
|
+
|
|
231
|
+
## Contributors
|
|
232
|
+
|
|
233
|
+
Please read [contributing guidelines here](https://tsed.devcontributing.html).
|
|
234
|
+
|
|
235
|
+
<a href="https://github.com/tsedio/tsed/graphs/contributors"><img src="https://opencollective.com/tsed/contributors.svg?width=890" /></a>
|
|
236
|
+
|
|
237
|
+
## Backers
|
|
238
|
+
|
|
239
|
+
Thank you to all our backers! 🙏 [[Become a backer](https://opencollective.com/tsed#backer)]
|
|
240
|
+
|
|
241
|
+
<a href="https://opencollective.com/tsed#backers" target="_blank"><img src="https://opencollective.com/tsed/tiers/backer.svg?width=890"></a>
|
|
242
|
+
|
|
243
|
+
## Sponsors
|
|
244
|
+
|
|
245
|
+
Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [[Become a sponsor](https://opencollective.com/tsed#sponsor)]
|
|
246
|
+
|
|
247
|
+
## License
|
|
248
|
+
|
|
249
|
+
The MIT License (MIT)
|
|
250
|
+
|
|
251
|
+
Copyright (c) 2016 - 2022 Romain Lenzotti
|
|
252
|
+
|
|
253
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
254
|
+
|
|
255
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
256
|
+
|
|
257
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import {StoreMerge} from "@tsed/core";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Set the type documentation for this class.
|
|
5
|
+
*
|
|
6
|
+
* See [swagger documentation](/tutorials/swagger.html)
|
|
7
|
+
*
|
|
8
|
+
* @decorator
|
|
9
|
+
* @swagger
|
|
10
|
+
* @param docs
|
|
11
|
+
*/
|
|
12
|
+
export function Docs(...docs: string[]) {
|
|
13
|
+
return StoreMerge("docs", docs);
|
|
14
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file Automatically generated by @tsed/barrels.
|
|
3
|
+
*/
|
|
4
|
+
export * from "./decorators/docs.js";
|
|
5
|
+
export * from "./interfaces/OpenApiSettings.js";
|
|
6
|
+
export * from "./middlewares/cssMiddleware.js";
|
|
7
|
+
export * from "./middlewares/jsMiddleware.js";
|
|
8
|
+
export * from "./middlewares/openApiMiddleware.js";
|
|
9
|
+
export * from "./middlewares/redirectMiddleware.js";
|
|
10
|
+
export * from "./services/OpenAPIBaseModule.js";
|
|
11
|
+
export * from "./services/OpenAPIService.js";
|
|
12
|
+
export * from "./utils/includeRoute.js";
|
|
13
|
+
export * from "./utils/matchPath.js";
|
|
14
|
+
export * from "./utils/readSpec.js";
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import {OpenSpec2, OpenSpec3, OpenSpecVersions, OS2Versions, OS3Versions} from "@tsed/openspec";
|
|
2
|
+
|
|
3
|
+
export interface SwaggerUIOptions {
|
|
4
|
+
configUrl?: string;
|
|
5
|
+
url?: string;
|
|
6
|
+
urls?: {url: string; name: string; primaryName?: string}[];
|
|
7
|
+
layout?: string;
|
|
8
|
+
validatorUrl?: string;
|
|
9
|
+
oauth?: any;
|
|
10
|
+
authorize?: any;
|
|
11
|
+
|
|
12
|
+
[key: string]: any;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface OpenApiSettingsBase {
|
|
16
|
+
/**
|
|
17
|
+
* The url subpath to access to the documentation.
|
|
18
|
+
*/
|
|
19
|
+
path: string;
|
|
20
|
+
/**
|
|
21
|
+
* Specify the spec version you want to generate.
|
|
22
|
+
*/
|
|
23
|
+
specVersion?: OpenSpecVersions;
|
|
24
|
+
/**
|
|
25
|
+
* Swagger file name. By default swagger.json
|
|
26
|
+
*/
|
|
27
|
+
fileName?: string;
|
|
28
|
+
/**
|
|
29
|
+
* The documentation key used by `@Docs` decorator to create several swagger documentations.
|
|
30
|
+
*/
|
|
31
|
+
doc?: string;
|
|
32
|
+
/**
|
|
33
|
+
* The path to the CSS file.
|
|
34
|
+
*/
|
|
35
|
+
cssPath?: string;
|
|
36
|
+
/**
|
|
37
|
+
* The path to the JS file.
|
|
38
|
+
*/
|
|
39
|
+
jsPath?: string;
|
|
40
|
+
/**
|
|
41
|
+
* The path to the ejs file to create html page.
|
|
42
|
+
*/
|
|
43
|
+
viewPath?: string | false;
|
|
44
|
+
/**
|
|
45
|
+
* Display the search field in the navbar.
|
|
46
|
+
*/
|
|
47
|
+
showExplorer?: boolean;
|
|
48
|
+
/**
|
|
49
|
+
* Load the base spec documentation from the specified path.
|
|
50
|
+
*/
|
|
51
|
+
specPath?: string;
|
|
52
|
+
/**
|
|
53
|
+
* Write the `swagger.json` spec documentation on the specified path.
|
|
54
|
+
*/
|
|
55
|
+
outFile?: string;
|
|
56
|
+
/**
|
|
57
|
+
* Display the documentation in the browser.
|
|
58
|
+
*/
|
|
59
|
+
hidden?: boolean;
|
|
60
|
+
/**
|
|
61
|
+
* Sort paths by alphabetical order
|
|
62
|
+
*/
|
|
63
|
+
sortPaths?: boolean;
|
|
64
|
+
/**
|
|
65
|
+
* A function to generate the operationId.
|
|
66
|
+
*/
|
|
67
|
+
operationIdFormatter?: (name: string, propertyKey: string, path: string) => string;
|
|
68
|
+
/**
|
|
69
|
+
* A pattern to generate the operationId. Format of operationId field (%c: class name, %m: method name).
|
|
70
|
+
*/
|
|
71
|
+
operationIdPattern?: string;
|
|
72
|
+
/**
|
|
73
|
+
*
|
|
74
|
+
*/
|
|
75
|
+
disableSpec?: boolean;
|
|
76
|
+
/**
|
|
77
|
+
* Include only controllers whose paths match the pattern list provided.
|
|
78
|
+
*/
|
|
79
|
+
pathPatterns?: string[];
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export interface Swagger2Settings extends OpenApiSettingsBase {
|
|
83
|
+
specVersion?: OS2Versions;
|
|
84
|
+
/**
|
|
85
|
+
* OpenSpec 2
|
|
86
|
+
*/
|
|
87
|
+
spec?: Partial<OpenSpec2>;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export interface OpenAPI3Settings extends OpenApiSettingsBase {
|
|
91
|
+
specVersion?: OS3Versions;
|
|
92
|
+
/**
|
|
93
|
+
* OpenSpec 3
|
|
94
|
+
*/
|
|
95
|
+
spec?: Partial<OpenSpec3>;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export type OpenApiSettings = Swagger2Settings | OpenAPI3Settings;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import {runInContext} from "@tsed/di";
|
|
2
|
+
import {PlatformTest} from "@tsed/platform-http/testing";
|
|
3
|
+
import Fs from "fs";
|
|
4
|
+
|
|
5
|
+
import {cssMiddleware} from "./cssMiddleware.js";
|
|
6
|
+
|
|
7
|
+
describe("cssMiddleware", () => {
|
|
8
|
+
beforeEach(PlatformTest.create);
|
|
9
|
+
afterEach(PlatformTest.reset);
|
|
10
|
+
beforeEach(() => {
|
|
11
|
+
vi.spyOn(Fs, "readFileSync").mockReturnValue(".css{}");
|
|
12
|
+
});
|
|
13
|
+
it("should create a middleware", async () => {
|
|
14
|
+
const ctx = PlatformTest.createRequestContext();
|
|
15
|
+
|
|
16
|
+
await runInContext(ctx, () => cssMiddleware("/path")());
|
|
17
|
+
|
|
18
|
+
expect(ctx.response.raw.headers).toEqual({
|
|
19
|
+
"content-type": "text/css",
|
|
20
|
+
"x-request-id": "id"
|
|
21
|
+
});
|
|
22
|
+
expect(ctx.response.raw.statusCode).toEqual(200);
|
|
23
|
+
expect(ctx.response.raw.data).toEqual(".css{}");
|
|
24
|
+
});
|
|
25
|
+
});
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import {context} from "@tsed/di";
|
|
2
|
+
import Fs from "fs";
|
|
3
|
+
import {resolve} from "path";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Expose a css file.
|
|
7
|
+
* @param path
|
|
8
|
+
*/
|
|
9
|
+
export function cssMiddleware(path: string) {
|
|
10
|
+
return () => {
|
|
11
|
+
const ctx = context();
|
|
12
|
+
|
|
13
|
+
const content = Fs.readFileSync(resolve(path), {encoding: "utf8"});
|
|
14
|
+
|
|
15
|
+
ctx.response
|
|
16
|
+
.setHeaders({
|
|
17
|
+
"Content-Type": "text/css"
|
|
18
|
+
})
|
|
19
|
+
.status(200)
|
|
20
|
+
.body(content);
|
|
21
|
+
};
|
|
22
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import {runInContext} from "@tsed/di";
|
|
2
|
+
import {PlatformTest} from "@tsed/platform-http/testing";
|
|
3
|
+
import Fs from "fs";
|
|
4
|
+
|
|
5
|
+
import {jsMiddleware} from "./jsMiddleware.js";
|
|
6
|
+
|
|
7
|
+
describe("jsMiddleware", () => {
|
|
8
|
+
beforeEach(PlatformTest.create);
|
|
9
|
+
afterEach(PlatformTest.reset);
|
|
10
|
+
beforeEach(() => {
|
|
11
|
+
vi.spyOn(Fs, "readFileSync").mockReturnValue("var test=1");
|
|
12
|
+
});
|
|
13
|
+
it("should create a middleware", async () => {
|
|
14
|
+
const ctx = PlatformTest.createRequestContext();
|
|
15
|
+
|
|
16
|
+
await runInContext(ctx, () => jsMiddleware("/path")());
|
|
17
|
+
|
|
18
|
+
expect(ctx.response.raw.headers).toEqual({
|
|
19
|
+
"content-type": "application/javascript",
|
|
20
|
+
"x-request-id": "id"
|
|
21
|
+
});
|
|
22
|
+
expect(ctx.response.raw.statusCode).toBe(200);
|
|
23
|
+
expect(ctx.response.raw.data).toBe("var test=1");
|
|
24
|
+
});
|
|
25
|
+
});
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import {context} from "@tsed/di";
|
|
2
|
+
import Fs from "fs";
|
|
3
|
+
import {resolve} from "path";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Expose a js file.
|
|
7
|
+
* @param path
|
|
8
|
+
*/
|
|
9
|
+
export function jsMiddleware(path: string) {
|
|
10
|
+
return () => {
|
|
11
|
+
const ctx = context();
|
|
12
|
+
|
|
13
|
+
const content = Fs.readFileSync(resolve(path), {encoding: "utf8"});
|
|
14
|
+
ctx.response.setHeaders({"Content-Type": "application/javascript"}).status(200).body(content);
|
|
15
|
+
};
|
|
16
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import {runInContext} from "@tsed/di";
|
|
2
|
+
import {PlatformTest} from "@tsed/platform-http/testing";
|
|
3
|
+
import Fs from "fs";
|
|
4
|
+
|
|
5
|
+
import {openApiMiddleware} from "./openApiMiddleware.js";
|
|
6
|
+
|
|
7
|
+
describe("openApiMiddleware", () => {
|
|
8
|
+
beforeEach(PlatformTest.create);
|
|
9
|
+
afterEach(PlatformTest.reset);
|
|
10
|
+
beforeEach(() => {
|
|
11
|
+
vi.spyOn(Fs, "readFileSync").mockReturnValue("var test=1");
|
|
12
|
+
});
|
|
13
|
+
it("should create a middleware", async () => {
|
|
14
|
+
const ctx = PlatformTest.createRequestContext();
|
|
15
|
+
const conf = {specVersion: "3.0.1"};
|
|
16
|
+
|
|
17
|
+
await runInContext(ctx, () => openApiMiddleware(conf as never)());
|
|
18
|
+
|
|
19
|
+
expect(ctx.response.raw.headers).toEqual({
|
|
20
|
+
"x-request-id": "id"
|
|
21
|
+
});
|
|
22
|
+
expect(ctx.response.raw.statusCode).toBe(200);
|
|
23
|
+
expect(ctx.response.raw.data).toEqual({
|
|
24
|
+
info: {
|
|
25
|
+
title: "Api documentation",
|
|
26
|
+
version: "1.0.0"
|
|
27
|
+
},
|
|
28
|
+
openapi: "3.0.1"
|
|
29
|
+
});
|
|
30
|
+
});
|
|
31
|
+
});
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import {context, injector} from "@tsed/di";
|
|
2
|
+
|
|
3
|
+
import type {OpenApiSettings} from "../interfaces/OpenApiSettings.js";
|
|
4
|
+
import {OpenAPIService} from "../services/OpenAPIService.js";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Return a middleware to expose the OpenAPI spec.
|
|
8
|
+
*/
|
|
9
|
+
export function openApiMiddleware(conf: OpenApiSettings) {
|
|
10
|
+
return async () => {
|
|
11
|
+
const ctx = context();
|
|
12
|
+
const spec = await injector().get(OpenAPIService).getOpenAPISpec(conf);
|
|
13
|
+
|
|
14
|
+
ctx.response.status(200).body(spec);
|
|
15
|
+
};
|
|
16
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import {runInContext} from "@tsed/di";
|
|
2
|
+
import {PlatformTest} from "@tsed/platform-http/testing";
|
|
3
|
+
|
|
4
|
+
import {redirectMiddleware} from "./redirectMiddleware.js";
|
|
5
|
+
|
|
6
|
+
describe("redirectMiddleware and redirect", () => {
|
|
7
|
+
beforeEach(PlatformTest.create);
|
|
8
|
+
afterEach(PlatformTest.reset);
|
|
9
|
+
it("should create a middleware", async () => {
|
|
10
|
+
const ctx = PlatformTest.createRequestContext();
|
|
11
|
+
vi.spyOn(ctx.response, "redirect").mockReturnValue(undefined as never);
|
|
12
|
+
|
|
13
|
+
ctx.request.raw.url = "/path";
|
|
14
|
+
ctx.request.raw.originalUrl = "/path";
|
|
15
|
+
ctx.request.raw.method = "GET";
|
|
16
|
+
|
|
17
|
+
await runInContext(ctx, () => redirectMiddleware("/path")());
|
|
18
|
+
|
|
19
|
+
expect(ctx.response.redirect).toHaveBeenCalledWith(302, "/path/");
|
|
20
|
+
});
|
|
21
|
+
it("should create a middleware and call next", async () => {
|
|
22
|
+
const ctx = PlatformTest.createRequestContext();
|
|
23
|
+
vi.spyOn(ctx.response, "redirect");
|
|
24
|
+
ctx.request.raw.url = "/path/";
|
|
25
|
+
ctx.request.raw.method = "GET";
|
|
26
|
+
ctx.request.raw.originalUrl = "/path/";
|
|
27
|
+
|
|
28
|
+
await runInContext(ctx, () => redirectMiddleware("/path")());
|
|
29
|
+
|
|
30
|
+
expect(ctx.response.redirect).not.toHaveBeenCalled();
|
|
31
|
+
});
|
|
32
|
+
});
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import {context} from "@tsed/di";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Redirect to the same path with a trailing slash
|
|
5
|
+
* @param path
|
|
6
|
+
*/
|
|
7
|
+
export function redirectMiddleware(path: string) {
|
|
8
|
+
return () => {
|
|
9
|
+
const ctx = context();
|
|
10
|
+
|
|
11
|
+
if (ctx.request.method?.toUpperCase() === "GET" && ctx.request.url === path && !ctx.request.url.match(/\/$/)) {
|
|
12
|
+
ctx.response.redirect(302, `${path}/`);
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import {basename} from "node:path";
|
|
2
|
+
|
|
3
|
+
import {Env} from "@tsed/core";
|
|
4
|
+
import {configuration, constant, inject, logger} from "@tsed/di";
|
|
5
|
+
import {normalizePath} from "@tsed/normalize-path";
|
|
6
|
+
import {application, OnReady, OnRoutesInit} from "@tsed/platform-http";
|
|
7
|
+
import {PlatformRouter, useContextHandler} from "@tsed/platform-router";
|
|
8
|
+
|
|
9
|
+
import type {OpenApiSettings} from "../interfaces/OpenApiSettings.js";
|
|
10
|
+
import {cssMiddleware} from "../middlewares/cssMiddleware.js";
|
|
11
|
+
import {jsMiddleware} from "../middlewares/jsMiddleware.js";
|
|
12
|
+
import {openApiMiddleware} from "../middlewares/openApiMiddleware.js";
|
|
13
|
+
import {redirectMiddleware} from "../middlewares/redirectMiddleware.js";
|
|
14
|
+
import {OpenAPIService} from "../services/OpenAPIService.js";
|
|
15
|
+
|
|
16
|
+
export abstract class OpenAPIBaseModule implements OnRoutesInit, OnReady {
|
|
17
|
+
abstract name: string;
|
|
18
|
+
abstract rootDir: string;
|
|
19
|
+
abstract settings: OpenApiSettings[];
|
|
20
|
+
protected openAPIService = inject(OpenAPIService);
|
|
21
|
+
protected env = constant<Env>("env");
|
|
22
|
+
protected disableRoutesSummary = constant<boolean>("logger.disableRoutesSummary");
|
|
23
|
+
private loaded = false;
|
|
24
|
+
|
|
25
|
+
$onRoutesInit() {
|
|
26
|
+
if (this.loaded) {
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
this.settings.forEach((conf: OpenApiSettings) => {
|
|
31
|
+
const {path = "/"} = conf;
|
|
32
|
+
|
|
33
|
+
application().use(path, useContextHandler(redirectMiddleware(path)));
|
|
34
|
+
application().use(path, this.createRouter(conf));
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
this.loaded = true;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
$onReady() {
|
|
41
|
+
// istanbul ignore next
|
|
42
|
+
if (configuration().getBestHost && !this.disableRoutesSummary) {
|
|
43
|
+
const host = configuration().getBestHost();
|
|
44
|
+
const url = host.toString();
|
|
45
|
+
|
|
46
|
+
const displayLog = (conf: OpenApiSettings) => {
|
|
47
|
+
const {path, fileName, doc, specVersion} = conf;
|
|
48
|
+
|
|
49
|
+
logger().info(
|
|
50
|
+
`[${doc || "default"}] ${specVersion === "2.0" ? "Swagger" : "OpenAPI"} JSON is available on ${url}${normalizePath(path, fileName!)}`
|
|
51
|
+
);
|
|
52
|
+
logger().info(`[${doc || "default"}] ${this.name} UI is available on ${url}${path}/`);
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
this.settings.forEach((conf) => {
|
|
56
|
+
displayLog(conf);
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
this.generateSpecFiles();
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
generateSpecFiles() {
|
|
64
|
+
return Promise.all(
|
|
65
|
+
this.settings.map(async (conf) => {
|
|
66
|
+
this.openAPIService.writeOpenAPISpec(conf);
|
|
67
|
+
})
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
protected createRouter(conf: OpenApiSettings) {
|
|
72
|
+
const {disableSpec, fileName, cssPath, jsPath, viewPath} = conf;
|
|
73
|
+
const router = new PlatformRouter();
|
|
74
|
+
|
|
75
|
+
if (!disableSpec) {
|
|
76
|
+
router.get(normalizePath("/", fileName!), useContextHandler(openApiMiddleware(conf)));
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
if (viewPath) {
|
|
80
|
+
if (cssPath) {
|
|
81
|
+
router.get(`/${basename(cssPath)}`, useContextHandler(cssMiddleware(cssPath)));
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
if (jsPath) {
|
|
85
|
+
router.get(`/${basename(jsPath)}`, useContextHandler(jsMiddleware(jsPath)));
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
return router;
|
|
90
|
+
}
|
|
91
|
+
}
|