Skip to content

Commit 505ae06

Browse files
authored
📝 Add docs: Node.js script alternative to update OpenAPI for generated clients (fastapi#10845)
1 parent 4de60e1 commit 505ae06

File tree

2 files changed

+40
-3
lines changed

2 files changed

+40
-3
lines changed

docs/en/docs/advanced/generate-clients.md

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -229,9 +229,17 @@ But for the generated client we could **modify** the OpenAPI operation IDs right
229229

230230
We could download the OpenAPI JSON to a file `openapi.json` and then we could **remove that prefixed tag** with a script like this:
231231

232-
```Python
233-
{!../../../docs_src/generate_clients/tutorial004.py!}
234-
```
232+
=== "Python"
233+
234+
```Python
235+
{!> ../../../docs_src/generate_clients/tutorial004.py!}
236+
```
237+
238+
=== "Node.js"
239+
240+
```Python
241+
{!> ../../../docs_src/generate_clients/tutorial004.js!}
242+
```
235243

236244
With that, the operation IDs would be renamed from things like `items-get_items` to just `get_items`, that way the client generator can generate simpler method names.
237245

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import * as fs from "fs";
2+
3+
const filePath = "./openapi.json";
4+
5+
fs.readFile(filePath, (err, data) => {
6+
const openapiContent = JSON.parse(data);
7+
if (err) throw err;
8+
9+
const paths = openapiContent.paths;
10+
11+
Object.keys(paths).forEach((pathKey) => {
12+
const pathData = paths[pathKey];
13+
Object.keys(pathData).forEach((method) => {
14+
const operation = pathData[method];
15+
if (operation.tags && operation.tags.length > 0) {
16+
const tag = operation.tags[0];
17+
const operationId = operation.operationId;
18+
const toRemove = `${tag}-`;
19+
if (operationId.startsWith(toRemove)) {
20+
const newOperationId = operationId.substring(toRemove.length);
21+
operation.operationId = newOperationId;
22+
}
23+
}
24+
});
25+
});
26+
fs.writeFile(filePath, JSON.stringify(openapiContent, null, 2), (err) => {
27+
if (err) throw err;
28+
});
29+
});

0 commit comments

Comments
 (0)