From a30c738ecfc271040721de37886e037eef06be3b Mon Sep 17 00:00:00 2001 From: Nathan Totten Date: Tue, 5 Dec 2023 14:25:45 -0500 Subject: [PATCH] Added route convert script --- docs/articles/convert-urls-to-openapi.md | 55 ++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 docs/articles/convert-urls-to-openapi.md diff --git a/docs/articles/convert-urls-to-openapi.md b/docs/articles/convert-urls-to-openapi.md new file mode 100644 index 00000000..2632a992 --- /dev/null +++ b/docs/articles/convert-urls-to-openapi.md @@ -0,0 +1,55 @@ +--- +title: Script to Convert URL Params to OpenAPI Format +--- + +This is an example script that shows how to convert URLs in your Zuplo OpenAPI +files to OpenAPI formatted parameters. + +```js +import fs from "fs/promises"; +import kabab from "kebab-case"; +import path from "path"; +import { pathToRegexp } from "path-to-regexp"; +import prettier from "prettier"; + +const files = await fs.readdir(path.join(process.cwd(), "config")); +await Promise.all( + files.map(async (file) => { + if (file.endsWith(".oas.json")) { + const specPath = path.join(process.cwd(), "config", file); + const content = await fs.readFile(specPath, "utf-8").then(JSON.parse); + const newPaths = {}; + Object.entries(content.paths).forEach(([path, entry]) => { + delete entry["x-zuplo-path"]; + const keys = []; + pathToRegexp(path, keys); + let newPath = path; + keys.forEach((key) => { + newPath = newPath.replace(`:${key.name}`, `{${kababCase(key.name)}}`); + }); + Object.entries(entry).forEach(([method, methodEntry]) => { + if (entry[method].parameters) { + entry[method].parameters.forEach((param) => { + if (param.in === "path") { + param.name = kababCase(param.name); + } + }); + } + }); + newPaths[newPath] = entry; + }); + + content.paths = newPaths; + + const json = JSON.stringify(content, null, 2); + const output = prettier.format(json, { parser: "json" }); + + await fs.writeFile(specPath, output, "utf-8"); + } + }), +); + +function kababCase(str) { + return kabab(str).replaceAll("-u-r-l", "-url").replaceAll("-a-p-i", "-api"); +} +```