Skip to content

Commit

Permalink
Handle customProps & customImport
Browse files Browse the repository at this point in the history
  • Loading branch information
fabien0102 committed Sep 13, 2019
1 parent 0db9d09 commit 0a3db29
Show file tree
Hide file tree
Showing 4 changed files with 73 additions and 31 deletions.
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -635,7 +635,7 @@ interface RestfulReactConfig {

// advanced configuration
customImport?: string;
customProperties?: {
customProps?: {
base?: string;
};
};
Expand All @@ -651,15 +651,15 @@ module.exports = {
myFirstBackend: {
output: "src/queries/myFirstBackend.tsx",
file: "specs/my-first-backend.yaml",
customProperties: {
customProps: {
base: `"http://my-first-backend.com"`,
},
},
configurableBackend: {
output: "src/queries/configurableBackend.tsx",
github: "contiamo:restful-react:master:docs/swagger.json",
customImport: `import { getConfig } from "../components/Config.tsx";`,
customProperties: {
customProps: {
base: `{getConfig("backendBasePath")}`,
},
},
Expand Down
12 changes: 8 additions & 4 deletions examples/restful-react.config.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
/**
* Integration config for `yarn integration:advanced`
* Example config for `yarn example:advanced`
*/

module.exports = {
"petstore-file": {
file: "integration/petstore.yaml",
output: "integration/petstoreFromFileSpecWithConfig.tsx",
file: "examples/petstore.yaml",
output: "examples/petstoreFromFileSpecWithConfig.tsx",
},
"petstore-github": {
github: "OAI:OpenAPI-Specification:master:examples/v3.0/petstore.yaml",
output: "integration/petstoreFromGithubSpecWithConfig.tsx",
output: "examples/petstoreFromGithubSpecWithConfig.tsx",
customImport: "/* a custom import */",
customProps: {
base: `"http://my-pet-store.com"`,
},
},
};
40 changes: 28 additions & 12 deletions src/bin/restful-react-import.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,23 +9,23 @@ import importOpenApi from "../scripts/import-open-api";

const log = console.log; // tslint:disable-line:no-console

interface Options {
// classic configuration
export interface Options {
output: string;
file?: string;
github?: string;
transformer?: string;
validation?: boolean;
}

interface ExternalConfigFile {
[backend: string]: Options & {
// advanced configuration
customImport?: string;
customProperties?: {
base?: string;
};
export type AdvancedOptions = Options & {
customImport?: string;
customProps?: {
base?: string;
};
};

export interface ExternalConfigFile {
[backend: string]: AdvancedOptions;
}

program.option("-o, --output [value]", "output file destination");
Expand All @@ -36,7 +36,7 @@ program.option("--validation", "add the validation step (provided by ibm-openapi
program.option("--config [value]", "override flags by a config file");
program.parse(process.argv);

const importSpecs = async (options: Options) => {
const importSpecs = async (options: AdvancedOptions) => {
const transformer = options.transformer ? require(join(process.cwd(), options.transformer)) : undefined;

if (!options.output) {
Expand All @@ -51,7 +51,14 @@ const importSpecs = async (options: Options) => {
const { ext } = parse(options.file);
const format = [".yaml", ".yml"].includes(ext.toLowerCase()) ? "yaml" : "json";

return importOpenApi(data, format, transformer, options.validation);
return importOpenApi({
data,
format,
transformer,
validation: options.validation,
customImport: options.customImport,
customProps: options.customProps,
});
} else if (options.github) {
let accessToken: string;
const githubTokenPath = join(__dirname, ".githubToken");
Expand Down Expand Up @@ -126,7 +133,16 @@ const importSpecs = async (options: Options) => {
options.github!.toLowerCase().includes(".yaml") || options.github!.toLowerCase().includes(".yml")
? "yaml"
: "json";
resolve(importOpenApi(body.data.repository.object.text, format, transformer, options.validation));
resolve(
importOpenApi({
data: body.data.repository.object.text,
format,
transformer,
validation: options.validation,
customImport: options.customImport,
customProps: options.customProps,
}),
);
});
});
} else {
Expand Down
46 changes: 34 additions & 12 deletions src/scripts/import-open-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {
import swagger2openapi from "swagger2openapi";

import YAML from "yamljs";
import { AdvancedOptions } from "../bin/restful-react-import";

/**
* Discriminator helper for `ReferenceObject`
Expand Down Expand Up @@ -243,6 +244,7 @@ export const generateRestfulComponent = (
operationIds: string[],
parameters: Array<ReferenceObject | ParameterObject> = [],
schemasComponents?: ComponentsObject,
customProps: AdvancedOptions["customProps"] = {},
) => {
if (!operation.operationId) {
throw new Error(`Every path must have a operationId - No operationId set for ${verb} ${route}`);
Expand Down Expand Up @@ -363,6 +365,9 @@ export const ${componentName} = (${
verb="${verb.toUpperCase()}"`
}
path={\`${route}\`}
${Object.entries(customProps)
.map(([key, value]) => `${key}=${value}`)
.join("\n ")}
{...props}
/>
);
Expand Down Expand Up @@ -525,17 +530,26 @@ Path : ${i.path}`),
/**
* Main entry of the generator. Generate restful-react component from openAPI.
*
* @param data raw data of the spec
* @param format format of the spec
* @param transformer custom function to transform your spec
* @param validation validate the spec with ibm-openapi-validator tool
* @param options.data raw data of the spec
* @param options.format format of the spec
* @param options.transformer custom function to transform your spec
* @param options.validation validate the spec with ibm-openapi-validator tool
*/
const importOpenApi = async (
data: string,
format: "yaml" | "json",
transformer?: (schema: OpenAPIObject) => OpenAPIObject,
validation = false,
) => {
const importOpenApi = async ({
data,
format,
transformer,
validation,
customImport,
customProps,
}: {
data: string;
format: "yaml" | "json";
transformer?: (schema: OpenAPIObject) => OpenAPIObject;
validation?: boolean;
customImport?: AdvancedOptions["customImport"];
customProps?: AdvancedOptions["customProps"];
}) => {
const operationIds: string[] = [];
let schema = await importSpecs(data, format);
if (transformer) {
Expand All @@ -553,7 +567,15 @@ const importOpenApi = async (
Object.entries(schema.paths).forEach(([route, verbs]: [string, PathItemObject]) => {
Object.entries(verbs).forEach(([verb, operation]: [string, OperationObject]) => {
if (["get", "post", "patch", "put", "delete"].includes(verb)) {
output += generateRestfulComponent(operation, verb, route, operationIds, verbs.parameters, schema.components);
output += generateRestfulComponent(
operation,
verb,
route,
operationIds,
verbs.parameters,
schema.components,
customProps,
);
}
});
});
Expand All @@ -576,7 +598,7 @@ const importOpenApi = async (
`/* Generated by restful-react */
import React from "react";
import { ${imports.join(", ")} } from "restful-react";
import { ${imports.join(", ")} } from "restful-react";${customImport ? `\n${customImport}\n` : ""}
export type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
Expand Down

0 comments on commit 0a3db29

Please sign in to comment.