Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Cloudflare] Add API client #35

Merged
merged 5 commits into from
Dec 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/late-singers-jog.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'cloudflare-api-js': minor
---

Initial release
2 changes: 1 addition & 1 deletion .github/workflows/update.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ jobs:

strategy:
matrix:
package: [[vercel-api-js], [netlify-api], [zoom-api-js], [keycloak-api], [dhis2-openapi]]
package: [[vercel-api-js], [netlify-api], [zoom-api-js], [keycloak-api], [dhis2-openapi], [cloudflare-api-js]]

steps:
- name: Checkout repo
Expand Down
4 changes: 4 additions & 0 deletions packages/cloudflare-api/.npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/node_modules
/rollup.config.js
/src
/openapi-codegen.config.ts
3 changes: 3 additions & 0 deletions packages/cloudflare-api/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Cloudflare API JavaScript SDK

Unofficial Cloudflare API JavaScript SDK built from the OpenAPI specification and with TypeScript types.
125 changes: 125 additions & 0 deletions packages/cloudflare-api/openapi-codegen.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
import { defineConfig } from '@openapi-codegen/cli';
import { Context } from '@openapi-codegen/cli/lib/types';
import { generateFetchers, generateSchemaTypes } from '@openapi-codegen/typescript';
import Case from "case";
import { OperationObject, PathItemObject } from 'openapi3-ts/oas30';
import { Project, VariableDeclarationKind } from 'ts-morph';
import ts from 'typescript';

export default defineConfig({
cloudflare: {
from: {
source: 'url',
url: 'https://raw.githubusercontent.com/cloudflare/api-schemas/main/openapi.json'
},
outputDir: 'src/api',
to: async (context) => {
const filenamePrefix = '';

// Add missing operation ids and clean them
context.openAPIDocument = cleanOperationIds({ openAPIDocument: context.openAPIDocument });

// Remove duplicated schemas
const schemaCount: Record<string, number> = {}
const rewrites = new Map<string, string>();
for (const path of Object.keys(context.openAPIDocument.components?.schemas ?? {})) {
const schemaName = Case.pascal(path);
if (schemaCount[schemaName] === undefined) {
schemaCount[schemaName] = 0;
}

schemaCount[schemaName] += 1;
if (schemaCount[schemaName] > 1 && context.openAPIDocument.components?.schemas?.[path]) {
rewrites.set(path, `${path}-${schemaCount[schemaName]}`);
context.openAPIDocument.components.schemas[`${path}-${schemaCount[schemaName]}`] = context.openAPIDocument.components.schemas[path];
delete context.openAPIDocument.components.schemas[path];
}
}

// Rewrite all $ref in components with new schema names
for (const [ref, newRef] of rewrites) {
context.openAPIDocument = JSON.parse(JSON.stringify(context.openAPIDocument).replace(new RegExp(`"#/components/schemas/${ref}"`, 'g'), `"#/components/schemas/${newRef}"`));
}

// Rewrite status code in components response with XX suffix to avoid invalid identifier (4XX -> 400, 5XX -> 500)
for (const [_, definition] of Object.entries(context.openAPIDocument.paths ?? {})) {
for (const [_, operation] of Object.entries(definition as PathItemObject)) {
const responses = (operation as OperationObject).responses;
if (responses) {
for (const [statusCode, response] of Object.entries(responses)) {
if (statusCode.endsWith('XX')) {
const newStatusCode = statusCode.slice(0, 1) + '00';
responses[newStatusCode] = response;
delete responses[statusCode];
}
}
}
}
}

const { schemasFiles } = await generateSchemaTypes(context, { filenamePrefix });
await generateFetchers(context, { filenamePrefix, schemasFiles });
await context.writeFile('extra.ts', buildExtraFile(context));
}
}
});

function buildExtraFile(context: Context) {
const project = new Project({
useInMemoryFileSystem: true,
compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget['ES2020'] }
});

const sourceFile = project.createSourceFile('extra.ts');

const operationsByPath = Object.fromEntries(
Object.entries(context.openAPIDocument.paths ?? {}).flatMap(([path, methods]) => {
return Object.entries(methods)
.filter(([method]) => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'].includes(method.toUpperCase()))
.map(([method, operation]: [string, any]) => [`${method.toUpperCase()} ${path}`, operation.operationId]);
})
);

sourceFile.addImportDeclaration({
namedImports: Object.values(operationsByPath),
moduleSpecifier: './components'
});

sourceFile.addVariableStatement({
isExported: true,
declarationKind: VariableDeclarationKind.Const,
declarations: [
{
name: 'operationsByPath',
initializer: `{
${Object.entries(operationsByPath)
.map(([path, operation]) => `"${path}": ${operation}`)
.join(',\n')}
}`
}
]
});

return sourceFile.getFullText();
}

function cleanOperationIds({
openAPIDocument,
}: {
openAPIDocument: Context['openAPIDocument'];
}) {
for (const [key, path] of Object.entries(openAPIDocument.paths as Record<string, PathItemObject>)) {
for (const method of ["get", "put", "post", "patch", "delete"] as const) {
if (path[method]) {
const operationId = path[method].operationId ?? `${method} ${key}`;
openAPIDocument.paths[key][method] = {
...openAPIDocument.paths[key][method],
operationId: Case.camel(operationId)
}
}
}

}

return openAPIDocument;
}
37 changes: 37 additions & 0 deletions packages/cloudflare-api/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
{
"name": "cloudflare-api-js",
"version": "0.0.1",
"description": "Cloudflare API client for Node.js",
"author": "SferaDev",
"license": "ISC",
"bugs": {
"url": "https://github.com/SferaDev/openapi-clients/issues"
},
"homepage": "https://github.com/SferaDev/openapi-clients#readme",
"main": "dist/index.cjs",
"module": "dist/index.mjs",
"typings": "dist/index.d.ts",
"exports": {
"./package.json": "./package.json",
".": {
"import": {
"types": "./dist/index.d.mts",
"default": "./dist/index.mjs"
},
"require": {
"types": "./dist/index.d.cts",
"default": "./dist/index.cjs"
}
}
},
"scripts": {
"tsc": "tsc --noEmit",
"build": "unbuild",
"prepack": "unbuild",
"generate": "openapi-codegen cloudflare"
},
"repository": {
"type": "git",
"url": "git+https://github.com/SferaDev/openapi-clients.git"
}
}
Loading
Loading