]> git.ipfire.org Git - thirdparty/fastapi/fastapi.git/commitdiff
📝 Add docs: Node.js script alternative to update OpenAPI for generated clients (...
authorAlejandra <90076947+alejsdev@users.noreply.github.com>
Tue, 26 Dec 2023 17:23:20 +0000 (12:23 -0500)
committerGitHub <noreply@github.com>
Tue, 26 Dec 2023 17:23:20 +0000 (18:23 +0100)
docs/en/docs/advanced/generate-clients.md
docs_src/generate_clients/tutorial004.js [new file with mode: 0644]

index e8d771f7123f481cca6b164c88bbf3f0145924d2..3a810baee1957f96fb27c7b95cb09812f1715bc7 100644 (file)
@@ -229,9 +229,17 @@ But for the generated client we could **modify** the OpenAPI operation IDs right
 
 We could download the OpenAPI JSON to a file `openapi.json` and then we could **remove that prefixed tag** with a script like this:
 
-```Python
-{!../../../docs_src/generate_clients/tutorial004.py!}
-```
+=== "Python"
+
+    ```Python
+    {!> ../../../docs_src/generate_clients/tutorial004.py!}
+    ```
+
+=== "Node.js"
+
+    ```Python
+    {!> ../../../docs_src/generate_clients/tutorial004.js!}
+    ```
 
 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.
 
diff --git a/docs_src/generate_clients/tutorial004.js b/docs_src/generate_clients/tutorial004.js
new file mode 100644 (file)
index 0000000..18dc382
--- /dev/null
@@ -0,0 +1,29 @@
+import * as fs from "fs";
+
+const filePath = "./openapi.json";
+
+fs.readFile(filePath, (err, data) => {
+  const openapiContent = JSON.parse(data);
+  if (err) throw err;
+
+  const paths = openapiContent.paths;
+
+  Object.keys(paths).forEach((pathKey) => {
+    const pathData = paths[pathKey];
+    Object.keys(pathData).forEach((method) => {
+      const operation = pathData[method];
+      if (operation.tags && operation.tags.length > 0) {
+        const tag = operation.tags[0];
+        const operationId = operation.operationId;
+        const toRemove = `${tag}-`;
+        if (operationId.startsWith(toRemove)) {
+          const newOperationId = operationId.substring(toRemove.length);
+          operation.operationId = newOperationId;
+        }
+      }
+    });
+  });
+  fs.writeFile(filePath, JSON.stringify(openapiContent, null, 2), (err) => {
+    if (err) throw err;
+  });
+});