Skip to content

Typescript 3 refs #62

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

Merged
merged 5 commits into from
Oct 31, 2019
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: 1 addition & 1 deletion nodemon.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,6 @@
"dist",
"./test/out"
],
"ext": "ts",
"ext": "ts,json,yml,yaml",
"optOut": true
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"main": "dist/index.js",
"scripts": {
"ts-node": "ts-node",
"test:lint": "eslint ./src/**/*.ts ./test/**/*.ts --fix",
"test:lint": "eslint './src/**/*.ts' './test/**/*.ts' --fix",
"test:run": "ts-node ./test/index.ts",
"test:build": "yarn test:run && tsc -p tsconfig.test.json",
"test:unit": "jest",
Expand Down
30 changes: 19 additions & 11 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Decoder } from 'io-ts';
import { Decoder, literal, type, union } from 'io-ts';
import { FSEntity, write } from './utils/fs';
import * as path from 'path';
import * as $RefParser from 'json-schema-ref-parser';
Expand Down Expand Up @@ -28,13 +28,9 @@ const getUnsafe: <E, A>(e: Either<E, A>) => A = either.fold(e => {
export const generate = <A>(options: GenerateOptions<A>): TaskEither<unknown, void> =>
taskEither.tryCatch(async () => {
const cwd = process.cwd();
log('cwd', cwd);

const out = path.isAbsolute(options.out) ? options.out : path.resolve(cwd, options.out);
log('out', out);

const spec = path.isAbsolute(options.spec) ? options.spec : path.resolve(cwd, options.spec);
log('spec', spec);
log('Processing', spec);

const $refs = await $RefParser.resolve(spec, {
dereference: {
Expand All @@ -46,15 +42,18 @@ export const generate = <A>(options: GenerateOptions<A>): TaskEither<unknown, vo
Object.entries($refs.values()),
array.reduce({}, (acc, [fullPath, spec]) => {
const relative = path.relative(cwd, fullPath);
log('Decoding', relative);
const decoded = reportIfFailed(options.decoder.decode(spec));
if (isLeft(decoded)) {
log('Unable to decode', relative, 'as OpenAPI spec. Treat it as an arbitrary json');
const specLike = specLikeCodec.decode(spec);
if (isLeft(specLike)) {
log('Unable to decode', relative, 'as spec. Treat it as an arbitrary json.');
// this is not a spec - treat as arbitrary json
return acc;
}
// use getUnsafe to fail fast if unable to decode a spec
const decoded = getUnsafe(reportIfFailed(options.decoder.decode(spec)));
log('Decoded', relative);
return {
...acc,
[relative]: decoded.right,
[relative]: decoded,
};
}),
);
Expand All @@ -68,3 +67,12 @@ export const generate = <A>(options: GenerateOptions<A>): TaskEither<unknown, vo

log('Done');
}, identity);

const specLikeCodec = union([
type({
swagger: literal('2.0'),
}),
type({
openapi: union([literal('3.0.0'), literal('3.0.1'), literal('3.0.2')]),
}),
]);
49 changes: 13 additions & 36 deletions src/language/typescript/2.0/serializers/operation-object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
SerializedType,
} from '../../common/data/serialized-type';
import { pipe } from 'fp-ts/lib/pipeable';
import { exists, getOrElse, map, none, Option, some } from 'fp-ts/lib/Option';
import { getOrElse, map, Option } from 'fp-ts/lib/Option';
import { flatten } from 'fp-ts/lib/Array';
import { serializeOperationResponses } from './responses-object';
import { fromArray, head, NonEmptyArray } from 'fp-ts/lib/NonEmptyArray';
Expand All @@ -22,7 +22,6 @@ import {
getSerializedKindDependency,
serializedDependency,
} from '../../common/data/serialized-dependency';
import { identity } from 'fp-ts/lib/function';
import { concatIf, concatIfL } from '../../../../utils/array';
import { unless, when } from '../../../../utils/string';
import { Context, getJSDoc, getURL, HTTPMethod, getKindValue } from '../../common/utils';
Expand Down Expand Up @@ -150,6 +149,7 @@ const getParameters = combineReader(
}
}
} else {
// if parameter has already been processed then skip it
if (contains(parameter, processedParameters)) {
continue;
}
Expand All @@ -169,7 +169,11 @@ const getParameters = combineReader(
break;
}
case 'query': {
const serialized = serializeQueryParameter(from, parameter);
const serialized = pipe(
serializeParameterObject(from, parameter),
either.map(getSerializedPropertyType(parameter.name, isRequired(parameter))),
either.map(fromSerializedType(isRequired(parameter))),
);
if (isLeft(serialized)) {
return serialized;
}
Expand Down Expand Up @@ -231,6 +235,7 @@ export const serializeOperationObject = combineReader(
pathItem: PathItemObject,
): Either<Error, SerializedType> => {
const parameters = getParameters(from, operation, pathItem);
const operationName = getOperationName(operation, method);

const serializedResponses = serializeOperationResponses(from, operation.responses);

Expand Down Expand Up @@ -274,33 +279,26 @@ export const serializeOperationObject = combineReader(
const hasBodyParameters = parameters.bodyParameters.length > 0;
const hasParameters = hasQueryParameters || hasBodyParameters;

const argsName = concatIf(hasParameters, parameters.pathParameters.map(p => p.name), [
'parameters',
]).join(',');
const argsType = concatIfL(hasParameters, parameters.serializedPathParameters.map(p => p.type), () => [
`parameters: { ${serializedParameters.type} }`,
]).join(',');

const paramsSummary = serializeParametersDescription([
...parameters.queryParameters,
...parameters.bodyParameters,
]);
const operationName = getOperationName(operation, method);

const type = `
${getJSDoc(array.compact([deprecated, operation.summary, paramsSummary]))}
${getJSDoc(array.compact([deprecated, operation.summary]))}
readonly ${operationName}: (${argsType}) => ${getKindValue(kind, serializedResponses.type)};
`;

const serializedUrl = getURL(url, parameters.serializedPathParameters);
const argsName = concatIf(hasParameters, parameters.pathParameters.map(p => p.name), [
'parameters',
]).join(',');

const io = `
${operationName}: (${argsName}) => {
${when(hasParameters, `const encoded = partial({ ${serializedParameters.io} }).encode(parameters);`)}

return e.httpClient.chain(
e.httpClient.request({
url: ${serializedUrl},
url: ${getURL(url, parameters.serializedPathParameters)},
method: '${method}',
${when(hasQueryParameters, 'query: encoded.query,')}
${when(hasBodyParameters, 'body: encoded.body,')}
Expand Down Expand Up @@ -341,27 +339,6 @@ const getOperationName = (operation: OperationObject, httpMethod: string) =>
getOrElse(() => httpMethod),
);

const serializeParametersDescription = (
parameters: Array<QueryParameterObject | BodyParameterObject>,
): Option<string> => {
const hasRequiredParameters = parameters.some(p =>
pipe(
p.required,
exists(identity),
),
);
return parameters.length === 0
? none
: some(hasRequiredParameters ? '@param { object } parameters' : '@param { object } [parameters]');
};

const serializeQueryParameter = (from: Ref, parameter: QueryParameterObject): Either<Error, SerializedParameter> =>
pipe(
serializeParameterObject(from, parameter),
either.map(getSerializedPropertyType(parameter.name, isRequired(parameter))),
either.map(fromSerializedType(isRequired(parameter))),
);

const serializeBodyParameterObjects = (
from: Ref,
parameters: NonEmptyArray<BodyParameterObject>,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import { combineReader } from '@devexperts/utils/dist/adt/reader.utils';
import { ask } from 'fp-ts/lib/Reader';
import { getIOName, getTypeName } from '../../common/utils';
import { addPathParts, Ref } from '../../../../utils/ref';
import { ResponsesDefinitionsObject } from '../../../../schema/2.0/responses-definitions-object';
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
import { serializeNonArraySchemaObject, serializeSchemaObject } from '../schema-object';
import { serializeSchemaObject } from '../schema-object';
import {
getSerializedArrayType,
getSerializedDictionaryType,
getSerializedObjectType,
getSerializedPropertyType,
getSerializedRecursiveType,
getSerializedRefType,
serializedType,
} from '../../../common/data/serialized-type';
import { serializedDependency } from '../../../common/data/serialized-dependency';
import { Either, right } from 'fp-ts/lib/Either';
import { assert, constant, property, record, string } from 'fast-check';
import { $refArbitrary } from '../../../../../utils/__tests__/ref.spec';
Expand All @@ -24,30 +22,6 @@ const chainEither = <A, EB, B>(f: (a: A) => Either<EB, B>) => <EA>(fa: Either<EA
);

describe('SchemaObject', () => {
describe('serializeNonArraySchemaObject', () => {
describe('should serialize', () => {
it('string', () => {
expect(serializeNonArraySchemaObject({ type: 'string', format: none, deprecated: none })).toEqual(
right(serializedType('string', 'string', [serializedDependency('string', 'io-ts')], [])),
);
});
it('boolean', () => {
expect(serializeNonArraySchemaObject({ type: 'boolean', format: none, deprecated: none })).toEqual(
right(serializedType('boolean', 'boolean', [serializedDependency('boolean', 'io-ts')], [])),
);
});
it('integer', () => {
expect(serializeNonArraySchemaObject({ type: 'integer', format: none, deprecated: none })).toEqual(
right(serializedType('number', 'number', [serializedDependency('number', 'io-ts')], [])),
);
});
it('number', () => {
expect(serializeNonArraySchemaObject({ type: 'number', format: none, deprecated: none })).toEqual(
right(serializedType('number', 'number', [serializedDependency('number', 'io-ts')], [])),
);
});
});
});
describe('serializeSchemaObject', () => {
describe('array', () => {
it('should serialize using getSerializedArrayType', () => {
Expand Down
Loading