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

Enable unsafe keep a json specification when compeller is invoked #19

Merged
merged 4 commits into from
Jan 27, 2022
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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,5 @@ node_modules
dist

*.tgz

tmp
16 changes: 16 additions & 0 deletions __tests__/compiler.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { join } from 'path';
import { compeller } from '../src';

const spec = {
Expand Down Expand Up @@ -47,5 +48,20 @@ describe('API Compiler tests', () => {
statusCode: '200',
});
});

it('keeps a local specification json when true', () => {
const stuff = compeller(spec, {
jsonSpecFile: join(__dirname, 'tmp', 'openapi.json'),
});

const { response } = stuff('/test', 'get');

const resp = response('200', { name: 'Type-safe reply' });

expect(resp).toEqual({
body: '{"name":"Type-safe reply"}',
statusCode: '200',
});
});
});
});
14 changes: 14 additions & 0 deletions __tests__/file-utils/write-specification.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { writeSpecification } from '../../src/file-utils/write-specification';

describe('writeSpecification', () => {
it('with directory and not file', () => {
writeSpecification('./tmp', {
info: {
title: 'spec',
version: '0.0.1',
},
openapi: '3.1.0',
paths: {},
});
});
});
7 changes: 7 additions & 0 deletions _templates/compeller/new/compeller.ejs.t
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
to: <%= directory %>/openapi/compeller.ts
---
import { compeller } from 'compeller'
import { OpenAPISpecification } from './spec'

cont compelled = compeller(OpenAPISpecification)
2 changes: 1 addition & 1 deletion _templates/compeller/new/spec.ejs.t
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export const OpenAPISpecification = {
},
openapi: '3.1.0',
paths: {
'v1//version': {
'v1/version': {
get: {
responses: {
'200': {
Expand Down
3 changes: 0 additions & 3 deletions jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,4 @@ module.exports = {
},
testEnvironment: 'node',
modulePathIgnorePatterns: ['<rootDir>/.*/fixtures/', '<rootDir>/example/*'],
moduleNameMapper: {
'^compeller/(.*)$': '<rootDir>/src/$1',
},
};
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
"@swc/jest": "^0.2.17",
"@tsconfig/node14": "^1.0.1",
"@types/jest": "^27.4.0",
"@types/node": "^17.0.12",
"embedme": "^1.22.0",
"husky": "^7.0.0",
"jest": "^27.4.7",
Expand Down
50 changes: 46 additions & 4 deletions src/compeller.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,40 @@
import Ajv, { JSONSchemaType } from 'ajv';
import { FromSchema } from 'json-schema-to-ts';
import { OpenAPIObject } from 'openapi3-ts';
import { writeSpecification } from './file-utils/write-specification';

export interface ICompellerOptions {
/**
* The content type for the responses, currently only 'application/json' is
* supported
*/
contentType?: string;
/**
* If boolean the default file location will be used
*
* @default false
*/
jsonSpecFile?: string | boolean;
/**
* Bind the relative path where compeller is used, to enable storing the
* specification along side the compeller entity
*/
relativePath?: string;
}

/**
* For now this is a mask on the OpenAPIObject, but later some fields will
* become mandatory.
*
* This is to enforce configuration, and remove the option for some fields to
* be any type, which is not the desired behavior for compeller.
*/
export interface ICompellerOpenAPIObject extends OpenAPIObject {}

const DEFAULT_OPTIONS: ICompellerOptions = {
contentType: 'application/json',
jsonSpecFile: false,
};

/**
* The open API Compiler will take in an OpenAPI specification and return type-
Expand All @@ -10,17 +44,23 @@ import { OpenAPIObject } from 'openapi3-ts';
* classes that define the Components and Schema's of the paths.
*
* @param {OpenAPIObject} spec - The OpenAPI specification document
* @param {string} contentType - The content type of requests and responses
* @default 'application/json'
* @param {ICompellerOptions} options - Compeller options
* @returns
*/
export const compeller = <
T extends OpenAPIObject,
T extends ICompellerOpenAPIObject,
U extends string = 'application/json'
>(
spec: T,
contentType = 'application/json'
{
contentType = 'application/json',
jsonSpecFile = false,
}: ICompellerOptions = DEFAULT_OPTIONS
) => {
if (jsonSpecFile) {
writeSpecification(jsonSpecFile, spec);
}

return <
P extends keyof T['paths'],
M extends keyof T['paths'][P],
Expand All @@ -32,6 +72,8 @@ export const compeller = <
const path = route as string;

/**
* Build a response object for the API with the required status and body
* format
*
* @param statusCode The response code that the API returns
* @param body The JSON body for the API that is associated with that
Expand Down
37 changes: 37 additions & 0 deletions src/file-utils/write-specification.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { writeFileSync } from 'fs';
import { join } from 'path';
import { ICompellerOpenAPIObject, ICompellerOptions } from '../compeller';

/**
* Write a JSON object to file if a valid path if provided
*
* @default `${__dirname}/openapi.json`
*
* @param jsonSpecFile If true a default path will be used as provided, other provide a fully qualified path
* @param spec The OpenAPI specification object
*/
export const writeSpecification = (
jsonSpecFile: ICompellerOptions['jsonSpecFile'],
spec: ICompellerOpenAPIObject
) => {
let fileName;

if (['production', 'prod'].includes(process?.env?.NODE_ENV || '')) return;

try {
fileName =
typeof jsonSpecFile === 'string'
? jsonSpecFile
: join(__dirname, 'openapi.json');

writeFileSync(fileName, JSON.stringify(spec, undefined, 2));
} catch (err) {
console.warn(
'Compeller could not write your schema to a file and has rescued to prevent unwanted runtime side-effects',
{
fileName,
error: err,
}
);
}
};
2 changes: 1 addition & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -838,7 +838,7 @@
dependencies:
"@types/node" "*"

"@types/node@*":
"@types/node@*", "@types/node@^17.0.12":
version "17.0.12"
resolved "https://registry.yarnpkg.com/@types/node/-/node-17.0.12.tgz#f7aa331b27f08244888c47b7df126184bc2339c5"
integrity sha512-4YpbAsnJXWYK/fpTVFlMIcUIho2AYCi4wg5aNPrG1ng7fn/1/RZfCIpRCiBX+12RVa34RluilnvCqD+g3KiSiA==
Expand Down