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

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
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
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.
73 changes: 73 additions & 0 deletions packages/cloudflare-api/openapi-codegen.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { defineConfig } from '@openapi-codegen/cli';
import { Context } from '@openapi-codegen/cli/lib/types';
import { generateFetchers, generateSchemaTypes, renameComponent } from '@openapi-codegen/typescript';
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 = '';

context.openAPIDocument = renameComponent({
openAPIDocument: context.openAPIDocument,
from: '#/components/schemas/0rtt',
to: '#/components/schemas/zerortt'
});

context.openAPIDocument = renameComponent({
openAPIDocument: context.openAPIDocument,
from: '#/components/schemas/0rtt_value',
to: '#/components/schemas/zerortt_value'
});

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();
}
27 changes: 27 additions & 0 deletions packages/cloudflare-api/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"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": {
"import": "./dist/index.mjs",
"require": "./dist/index.cjs"
},
"scripts": {
"tsc": "tsc --noEmit",
"build": "rimraf dist && rollup -c",
"generate": "openapi-codegen cloudflare"
},
"repository": {
"type": "git",
"url": "git+https://github.com/SferaDev/openapi-clients.git"
}
}
26 changes: 26 additions & 0 deletions packages/cloudflare-api/rollup.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import typescript from "@rollup/plugin-typescript";
import builtins from "builtin-modules";
import dts from "rollup-plugin-dts";

export default [
{
input: "./src/index.ts",
output: [
{
file: "dist/index.cjs",
format: "cjs",
},
{
file: "dist/index.mjs",
format: "esm",
},
],
external: builtins,
plugins: [typescript()],
},
{
input: "./src/index.ts",
output: [{ file: "dist/index.d.ts", format: "es" }],
plugins: [dts()],
},
];
97 changes: 97 additions & 0 deletions packages/cloudflare-api/src/api/fetcher.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import { FetchImpl } from '../utils/fetch';

export type FetcherExtraProps = {
token: string;
fetchImpl: FetchImpl;
};

export const baseUrl = 'https://api.cloudflare.com/client/v4';

export type ErrorWrapper<TError> = TError | { status: 'unknown'; payload: string };

export type FetcherOptions<TBody, THeaders, TQueryParams, TPathParams> = {
url: string;
method: string;
body?: TBody | undefined;
headers?: THeaders | undefined;
queryParams?: TQueryParams | undefined;
pathParams?: TPathParams | undefined;
signal?: AbortSignal | undefined;
} & FetcherExtraProps;

export async function fetch<
TData,
TError,
TBody extends {} | FormData | undefined | null,
THeaders extends {},
TQueryParams extends {},
TPathParams extends {}
>({
url,
method,
body,
headers,
pathParams,
queryParams,
signal,
token,
fetchImpl
}: FetcherOptions<TBody, THeaders, TQueryParams, TPathParams>): Promise<TData> {
try {
const requestHeaders: HeadersInit = {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
...headers
};

/**
* As the fetch API is being used, when multipart/form-data is specified
* the Content-Type header must be deleted so that the browser can set
* the correct boundary.
* https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects#sending_files_using_a_formdata_object
*/
if (requestHeaders['Content-Type']?.toLowerCase().includes('multipart/form-data')) {
delete requestHeaders['Content-Type'];
}

const response = await fetchImpl(`${baseUrl}${resolveUrl(url, queryParams, pathParams)}`, {
signal,
method: method.toUpperCase(),
body: body ? (body instanceof FormData ? body : JSON.stringify(body)) : undefined,
headers: requestHeaders
});
if (!response.ok) {
let error: ErrorWrapper<TError>;
try {
error = await response.json();
} catch (e) {
error = {
status: 'unknown' as const,
payload: e instanceof Error ? `Unexpected error (${e.message})` : 'Unexpected error'
};
}

throw error;
}

if (response.headers?.get('content-type')?.includes('json')) {
return await response.json();
} else {
// if it is not a json response, assume it is a blob and cast it to TData
return (await response.text()) as unknown as TData;
}
} catch (e) {
let errorObject: Error = {
name: 'unknown' as const,
message: e instanceof Error ? `Network error (${e.message})` : 'Network error',
stack: e as string
};
throw errorObject;
}
}

const resolveUrl = (url: string, queryParams: Record<string, string> = {}, pathParams: Record<string, string> = {}) => {
let query = new URLSearchParams(queryParams).toString();
if (query) query = `?${query}`;
return url.replace(/\{\w*\}/g, (key) => pathParams[key.slice(1, -1)] ?? '') + query;
};
Loading
Loading