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

Feature/arbitrary file downloads for oas 3 #144

Merged
Show file tree
Hide file tree
Changes from 4 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
149 changes: 103 additions & 46 deletions src/language/typescript/3.0/serializers/operation-object.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,4 @@
import {
getJSDoc,
getKindValue,
getSafePropertyName,
getTypeName,
getURL,
HTTPMethod,
SUCCESSFUL_CODES,
XHRResponseType,
} from '../../common/utils';
import { getJSDoc, getKindValue, getSafePropertyName, getTypeName, getURL, HTTPMethod } from '../../common/utils';
import {
getSerializedPropertyType,
getSerializedObjectType,
Expand Down Expand Up @@ -38,13 +29,13 @@ import {
} from '../../common/data/serialized-path-parameter';
import { concatIf } from '../../../../utils/array';
import { when } from '../../../../utils/string';
import { serializeRequestBodyObject } from './request-body-object';
import { getRequestMedia, serializeRequestBodyObject } from './request-body-object';
import { ResolveRefContext, fromString, getRelativePath, Ref } from '../../../../utils/ref';
import { OperationObject } from '../../../../schema/3.0/operation-object';
import { ParameterObject, ParameterObjectCodec } from '../../../../schema/3.0/parameter-object';
import { RequestBodyObjectCodec } from '../../../../schema/3.0/request-body-object';
import { chain, isSome, none, Option, some, map, fromEither, fold } from 'fp-ts/lib/Option';
import { constFalse } from 'fp-ts/lib/function';
import { constFalse, flow } from 'fp-ts/lib/function';
import { clientRef } from '../../common/bundled/client';
import { Kind } from '../../../../utils/types';
import { ReferenceObjectCodec } from '../../../../schema/3.0/reference-object';
Expand All @@ -58,15 +49,13 @@ import {
SerializedFragment,
} from '../../common/data/serialized-fragment';
import { SchemaObjectCodec } from '../../../../schema/3.0/schema-object';
import { lookup, keys } from 'fp-ts/lib/Record';
import { ResponseObjectCodec } from '../../../../schema/3.0/response-object';
import {
fromSerializedHeaderParameter,
getSerializedHeaderParameterType,
SerializedHeaderParameter,
} from '../../common/data/serialized-header-parameters';

const getOperationName = (pattern: string, operation: OperationObject, method: HTTPMethod): string =>
export const getOperationName = (pattern: string, operation: OperationObject, method: HTTPMethod): string =>
pipe(
operation.operationId,
option.getOrElse(() => `${method}_${getSafePropertyName(pattern)}`),
Expand Down Expand Up @@ -286,27 +275,19 @@ export const serializeOperationObject = combineReader(
);

const serializedResponses = serializeResponsesObject(from)(operation.responses);
const responseType: XHRResponseType = pipe(
SUCCESSFUL_CODES,
array.findFirstMap(code => lookup(code, operation.responses)),
chain(response =>
ReferenceObjectCodec.is(response)
? fromEither(e.resolveRef(response.$ref, ResponseObjectCodec))
: some(response),
const serializedContentType = pipe(
operation.requestBody,
chain(requestBody =>
ReferenceObjectCodec.is(requestBody)
? fromEither(e.resolveRef(requestBody.$ref, RequestBodyObjectCodec))
: some(requestBody),
),
chain(response => response.content),
map(keys),
map(request => request.content),
chain(getRequestMedia),
map(({ key }) => key),
fold(
() => 'json',
types => {
if (types.includes('application/octet-stream')) {
return 'blob';
}
if (types.includes('text/plain')) {
return 'text';
}
return 'json';
},
() => '',
contentType => `'Content-type': '${contentType}',`,
),
);

Expand All @@ -319,6 +300,7 @@ export const serializeOperationObject = combineReader(
const hasBodyParameter = isSome(parameters.serializedBodyParameter);
const hasHeaderParameters = isSome(parameters.serializedHeadersParameter);
const hasParameters = hasQueryParameters || hasBodyParameter || hasHeaderParameters;
const hasResponseMap = either.isRight(serializedResponses);

const bodyType = pipe(
parameters.serializedBodyParameter,
Expand All @@ -333,7 +315,7 @@ export const serializeOperationObject = combineReader(

const queryType = pipe(
parameters.serializedQueryParameter,
option.map(query => `query: ${query.type},`),
option.map(query => `query: ${query.type};`),
option.getOrElse(() => ''),
);
const queryIO = pipe(
Expand All @@ -344,7 +326,7 @@ export const serializeOperationObject = combineReader(

const headersType = pipe(
parameters.serializedHeadersParameter,
option.map(headers => `headers: ${headers.type}`),
option.map(headers => `headers: ${headers.type};`),
option.getOrElse(() => ''),
);

Expand All @@ -353,42 +335,102 @@ export const serializeOperationObject = combineReader(
option.map(headers => `const headers = ${headers.io}.encode(parameters.headers)`),
option.getOrElse(() => ''),
);
const accepArg = hasResponseMap ? 'accept?: A;' : '';

const argsType = concatIf(
hasParameters,
hasParameters || hasResponseMap,
parameters.serializedPathParameters.map(p => p.type),
[`parameters: { ${queryType}${bodyType}${headersType} }`],
[`parameters${hasParameters ? '' : '?'}: { ${queryType}${bodyType}${headersType}${accepArg} }`],
).join(',');

const type = `
const type = pipe(
serializedResponses,
either.fold(
sr => `
${getJSDoc(array.compact([deprecated, operation.summary]))}
readonly ${operationName}: (${argsType}) => ${getKindValue(kind, serializedResponses.type)};
`;
readonly ${operationName}: (${argsType}) => ${getKindValue(kind, sr.schema.type)};
`,
sr => `
${getJSDoc(array.compact([deprecated, operation.summary]))}
Geksanit marked this conversation as resolved.
Show resolved Hide resolved
readonly ${operationName}: <A extends keyof MapToResponse${operationName} = '${
sr[0].mediaType
}'>(${argsType}) => ${getKindValue(kind, `MapToResponse${operationName}[A]`)};
`,
),
);

const argsIO = concatIf(
hasParameters,
hasParameters || hasResponseMap,
parameters.pathParameters.map(p => p.name),
['parameters'],
).join(',');

const decode = pipe(
serializedResponses,
either.fold(
sr => `${sr.schema.io}.decode(value)`,
() => `decode(accept, value)`,
),
);
const acceptIO = pipe(
serializedResponses,
either.fold(
sr => `const accept = '${sr.mediaType}';`,
sr =>
`const rawAccept = (parameters && parameters.accept)!;
const accept = (rawAccept || '${sr[0].mediaType}') as typeof rawAccept;`,
),
);

const mapToIO = pipe(
serializedResponses,
either.fold(
() => '',
sr => {
const rows = sr.map(s => `'${s.mediaType}': ${s.schema.io}`);
return `const mapToIO = { ${rows.join()} };`;
},
),
);

const decodeIO = pipe(
serializedResponses,
either.fold(
() => '',
() =>
`const decode = <A extends keyof MapToResponse${operationName}>(a: A, b: unknown) =>
(mapToIO[a].decode(b) as unknown) as Either<Errors, MapToResponse${operationName}[A]>;`,
),
);

const requestHeaders = `{
Accept: accept,
${serializedContentType}
}`;

const io = `
${operationName}: (${argsIO}) => {
${bodyIO}
${queryIO}
${headersIO}
${acceptIO}
${mapToIO}
${decodeIO}
const responseType = getResponseTypeFromMediaType(accept);
const requestHeaders = ${requestHeaders}

return e.httpClient.chain(
e.httpClient.request({
url: ${getURL(pattern, parameters.serializedPathParameters)},
method: '${method}',
responseType: '${responseType}',
responseType,
${when(hasQueryParameters, 'query,')}
${when(hasBodyParameter, 'body,')}
${when(hasHeaderParameters, 'headers')}
headers: {${hasHeaderParameters ? '...headers,' : ''} ...requestHeaders}
}),
value =>
pipe(
${serializedResponses.io}.decode(value),
${decode},
either.mapLeft(ResponseValidationError.create),
either.fold(error => e.httpClient.throwError(error), decoded => e.httpClient.of(decoded)),
),
Expand All @@ -397,11 +439,26 @@ export const serializeOperationObject = combineReader(
`;

const dependencies = [
serializedDependency('getResponseTypeFromMediaType', '../utils/utils'),
serializedDependency('ResponseValidationError', getRelativePath(from, clientRef)),
serializedDependency('pipe', 'fp-ts/lib/pipeable'),
serializedDependency('either', 'fp-ts'),
getSerializedKindDependency(kind),
...serializedResponses.dependencies,
...pipe(
serializedResponses,
either.fold(
s => s.schema.dependencies,
flow(
array.map(s => s.schema.dependencies),
array.flatten,
arr => [
...arr,
serializedDependency('Errors', 'io-ts'),
serializedDependency('Either', 'fp-ts/lib/Either'),
],
),
),
),
...array.flatten([
...parameters.serializedPathParameters.map(p => p.dependencies),
...array.compact([
Expand Down
11 changes: 10 additions & 1 deletion src/language/typescript/3.0/serializers/paths-object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { applyTo } from '../../../../utils/function';
import { PathsObject } from '../../../../schema/3.0/paths-object';
import { clientRef } from '../../common/bundled/client';
import { getControllerName } from '../../common/utils';
import { serializeResponseMaps } from './response-maps';

const serializeGrouppedPaths = combineReader(
serializePathItemObject,
Expand All @@ -35,13 +36,19 @@ const serializeGrouppedPaths = combineReader(
sequenceEither,
either.map(foldSerializedTypes),
);
const serializedResponseMaps = pipe(
serializeDictionary(groupped, (pattern, item) => serializeResponseMaps(pattern, item, from)),
sequenceEither,
either.map(foldSerializedTypes),
);

return combineEither(
serializedHKT,
serializedKind,
serializedKind2,
clientRef,
(serializedHKT, serializedKind, serializedKind2, clientRef) => {
serializedResponseMaps,
(serializedHKT, serializedKind, serializedKind2, clientRef, serializedMaps) => {
const dependencies = serializeDependencies([
...serializedHKT.dependencies,
...serializedKind.dependencies,
Expand All @@ -56,6 +63,8 @@ const serializeGrouppedPaths = combineReader(
`${from.name}.ts`,
`
${dependencies}

${serializedMaps.type}

export interface ${from.name}<F> {
${serializedHKT.type}
Expand Down
60 changes: 43 additions & 17 deletions src/language/typescript/3.0/serializers/request-body-object.ts
Original file line number Diff line number Diff line change
@@ -1,33 +1,59 @@
import { serializeSchemaObject } from './schema-object';
import { getSerializedRefType, SerializedType } from '../../common/data/serialized-type';
import {
getSerializedBlobType,
getSerializedRefType,
SerializedType,
SERIALIZED_STRING_TYPE,
} from '../../common/data/serialized-type';
import { Either, mapLeft } from 'fp-ts/lib/Either';
import { pipe } from 'fp-ts/lib/pipeable';
import { either, option, record } from 'fp-ts';
import { either, option } from 'fp-ts';
import { fromString, Ref } from '../../../../utils/ref';
import { RequestBodyObject } from '../../../../schema/3.0/request-body-object';
import { ReferenceObjectCodec, ReferenceObject } from '../../../../schema/3.0/reference-object';
import { SchemaObject } from '../../../../schema/3.0/schema-object';
import { getKeyMatchValue, getResponseTypeFromMediaType, XHRResponseType } from '../../common/utils';
import { MediaTypeObject } from '../../../../schema/3.0/media-type-object';

const requestMediaRegexp = /^(video|audio|image|application|text|multipart\/form-data)/;
export const getRequestMedia = (content: Record<string, MediaTypeObject>) =>
getKeyMatchValue(content, requestMediaRegexp);

export const serializeRequestBodyObject = (from: Ref, body: RequestBodyObject): Either<Error, SerializedType> =>
pipe(
getSchema(body),
either.chain(schema =>
ReferenceObjectCodec.is(schema)
getRequestMedia(body.content),
option.chain(({ key: mediaType, value: { schema } }) =>
pipe(
schema,
option.map(schema => ({ mediaType, schema })),
),
),
either.fromOption(() => new Error('No schema found for ReqeustBodyObject')),
either.chain(({ mediaType, schema }) => {
const resType = getResponseTypeFromMediaType(mediaType);
return serializeRequestSchema(resType, schema, from);
}),
);

const serializeRequestSchema = (
responseType: XHRResponseType,
schema: ReferenceObject | SchemaObject,
from: Ref,
): Either<Error, SerializedType> => {
switch (responseType) {
case 'json':
return ReferenceObjectCodec.is(schema)
? pipe(
schema.$ref,
fromString,
fromString(schema.$ref),
mapLeft(
() => new Error(`Invalid MediaObject.content.$ref "${schema.$ref}" for RequestBodyObject`),
),
either.map(getSerializedRefType(from)),
)
: serializeSchemaObject(from)(schema),
),
);

const getSchema = (requestBodyObject: RequestBodyObject): Either<Error, ReferenceObject | SchemaObject> =>
pipe(
record.lookup('application/json', requestBodyObject.content),
option.chain(media => media.schema),
either.fromOption(() => new Error('No schema found for ReqeustBodyObject')),
);
: serializeSchemaObject(from)(schema);
case 'text':
return either.right(SERIALIZED_STRING_TYPE);
case 'blob':
return getSerializedBlobType(from);
}
};
Loading