Skip to content

Commit

Permalink
fix: make types less voidable
Browse files Browse the repository at this point in the history
  • Loading branch information
jrea committed Jun 14, 2022
1 parent d32369b commit d3ba4d5
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 89 deletions.
9 changes: 4 additions & 5 deletions lib/nile/templates/apis.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export interface {{classname}}Interface {
* @throws {RequiredError}
* @memberof {{classname}}Interface
*/
{{nickname}}({{#allParams.0}}requestParameters{{^allParams.0.required}}?{{/allParams.0.required}}: {{#prefixParameterInterfaces}}{{classname}}{{/prefixParameterInterfaces}}{{operationIdCamelCase}}Request, {{/allParams.0}}initOverrides?: RequestInit): Promise<{{#returnType}}void | {{/returnType}}{{{returnType}}}{{^returnType}}void{{/returnType}}>;
{{nickname}}({{#allParams.0}}requestParameters{{^allParams.0.required}}?{{/allParams.0.required}}: {{#prefixParameterInterfaces}}{{classname}}{{/prefixParameterInterfaces}}{{operationIdCamelCase}}Request, {{/allParams.0}}initOverrides?: RequestInit): Promise<{{{returnType}}}{{^returnType}}void{{/returnType}}>;
{{/operation}}
Expand Down Expand Up @@ -113,7 +113,7 @@ export class {{classname}} extends runtime.BaseAPI {
```
*/
async {{nickname}}({{#allParams.0}}requestParameters: {{#prefixParameterInterfaces}}{{classname}}{{/prefixParameterInterfaces}}{{operationIdCamelCase}}Request, {{/allParams.0}}initOverrides?: RequestInit): Promise<{{#returnType}}void | {{/returnType}}{{{returnType}}}{{^returnType}}void{{/returnType}}> {
async {{nickname}}({{#allParams.0}}requestParameters: {{#prefixParameterInterfaces}}{{classname}}{{/prefixParameterInterfaces}}{{operationIdCamelCase}}Request, {{/allParams.0}}initOverrides?: RequestInit): Promise<{{{returnType}}}{{^returnType}}void{{/returnType}}> {
{{#allParams}}
{{#required}}
Expand Down Expand Up @@ -356,9 +356,8 @@ export class {{classname}} extends runtime.BaseAPI {
const request = new runtime.JSONApiResponse(response{{^withoutRuntimeChecks}}, (jsonValue) => {{returnBaseType}}FromJSON(jsonValue){{/withoutRuntimeChecks}});
const val = await request.value();
if ('{{{returnType}}}'.toLowerCase() === 'token' && val && 'token' in val) {
if (typeof val['token'] === 'string'){
this.authToken = val['token'];
}
// @ts-ignore
this.authToken = val['token'];
}
return val;
{{/isMap}}
Expand Down
132 changes: 60 additions & 72 deletions lib/nile/templates/runtime.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -91,9 +91,8 @@ export const DefaultConfig = new Configuration();
export class BaseAPI {
private middleware: Middleware[];
public workspace?: string;
constructor(protected configuration = DefaultConfig) {
this.middleware = configuration.middleware;
this.workspace = configuration.workspace;
Expand All @@ -115,33 +114,28 @@ export class BaseAPI {
return this.withMiddleware<T>(...middlewares);
}

protected async request(context: RequestOpts, initOverrides?: RequestInit | InitOverideFunction): Promise<void | Response> {
protected async request(context: RequestOpts, initOverrides?: RequestInit | InitOverrideFunction): Promise<Response> {
const { url, init } = await this.createFetchParams(context, initOverrides);
const response = await this.fetchApi(url, init);
// requests are cancelable, silently fail
if (response) {
if (response.status >= 200 && response.status < 300) {
return response;
}
if (response.status >= 200 && response.status < 300) {
return response;
}

let res;
try {
res = await response.json();
} catch (e) {
/* do the default */
}
if (res && 'message' in res) {
const { message } = res;
throw new ResponseError(response, message);
}

throw new ResponseError(response, 'Response returned an error code');
let res;
try {
res = await response.json();
} catch (e) {
/* do the default */
}

return Promise.resolve(undefined);
if (res && 'message' in res) {
const { message } = res;
throw new ResponseError(response, message);
}

throw new ResponseError(response, 'Response returned an error code');
}

private async createFetchParams(context: RequestOpts, initOverrides?: RequestInit | InitOverideFunction) {
private async createFetchParams(context: RequestOpts, initOverrides?: RequestInit | InitOverrideFunction) {
let url = this.configuration.basePath + context.path;
if (context.query !== undefined && Object.keys(context.query).length !== 0) {
// only add the querystring to the URL if there are query parameters.
Expand Down Expand Up @@ -196,17 +190,15 @@ export class BaseAPI {
}) || fetchParams;
}
}
let response = await (this.configuration.fetchApi || fetch)(fetchParams.url, fetchParams.init).catch(e=> console.warn(e));
if (response) {
for (const middleware of this.middleware) {
if (middleware.post) {
response = await middleware.post({
fetch: this.fetchApi,
url: fetchParams.url,
init: fetchParams.init,
response: response.clone(),
}) || response;
}
let response = await (this.configuration.fetchApi || fetch)(fetchParams.url, fetchParams.init);
for (const middleware of this.middleware) {
if (middleware.post) {
response = await middleware.post({
fetch: this.fetchApi,
url: fetchParams.url,
init: fetchParams.init,
response: response.clone(),
}) || response;
}
}
return response;
Expand Down Expand Up @@ -258,12 +250,12 @@ export type FetchAPI = WindowOrWorkerGlobalScope['fetch'];
export type Json = any;
export type HTTPMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | 'HEAD';
export type HTTPHeaders = { [key: string]: string };
export type HTTPQuery = { [key: string]: string | number | null | boolean | Array<string | number | null | boolean> | HTTPQuery };
export type HTTPQuery = { [key: string]: string | number | null | boolean | Array<string | number | null | boolean> | Set<string | number | null | boolean> | HTTPQuery };
export type HTTPBody = Json | FormData | URLSearchParams;
export type HTTPRequestInit = { headers?: HTTPHeaders; method: HTTPMethod; credentials?: RequestCredentials; body?: HTTPBody }
export type ModelPropertyNaming = 'camelCase' | 'snake_case' | 'PascalCase' | 'original';

export type InitOverideFunction = (requestContext: { init: HTTPRequestInit, context: RequestOpts }) => Promise<RequestInit>
export type InitOverrideFunction = (requestContext: { init: HTTPRequestInit, context: RequestOpts }) => Promise<RequestInit>

export interface FetchParams {
url: string;
Expand All @@ -287,26 +279,31 @@ export function exists(json: any, key: string) {

export function querystring(params: HTTPQuery, prefix: string = ''): string {
return Object.keys(params)
.map((key) => {
const fullKey = prefix + (prefix.length ? `[${key}]` : key);
const value = params[key];
if (value instanceof Array) {
const multiValue = value.map(singleValue => encodeURIComponent(String(singleValue)))
.join(`&${encodeURIComponent(fullKey)}=`);
return `${encodeURIComponent(fullKey)}=${multiValue}`;
}
if (value instanceof Date) {
return `${encodeURIComponent(fullKey)}=${encodeURIComponent(value.toISOString())}`;
}
if (value instanceof Object) {
return querystring(value as HTTPQuery, fullKey);
}
return `${encodeURIComponent(fullKey)}=${encodeURIComponent(String(value))}`;
})
.map(key => querystringSingleKey(key, params[key], prefix))
.filter(part => part.length > 0)
.join('&');
}

function querystringSingleKey(key: string, value: string | number | null | undefined | boolean | Array<string | number | null | boolean> | Set<string | number | null | boolean> | HTTPQuery, keyPrefix: string = ''): string {
const fullKey = keyPrefix + (keyPrefix.length ? `[${key}]` : key);
if (value instanceof Array) {
const multiValue = value.map(singleValue => encodeURIComponent(String(singleValue)))
.join(`&${encodeURIComponent(fullKey)}=`);
return `${encodeURIComponent(fullKey)}=${multiValue}`;
}
if (value instanceof Set) {
const valueAsArray = Array.from(value);
return querystringSingleKey(key, valueAsArray, keyPrefix);
}
if (value instanceof Date) {
return `${encodeURIComponent(fullKey)}=${encodeURIComponent(value.toISOString())}`;
}
if (value instanceof Object) {
return querystring(value as HTTPQuery, fullKey);
}
return `${encodeURIComponent(fullKey)}=${encodeURIComponent(String(value))}`;
}

{{^withoutRuntimeChecks}}
export function mapValues(data: any, fn: (item: any) => any) {
return Object.keys(data).reduce(
Expand Down Expand Up @@ -348,7 +345,7 @@ export interface Middleware {
}

export interface ApiResponse<T> {
raw: void | Response;
raw: Response;
value(): Promise<T>;
}

Expand All @@ -357,42 +354,33 @@ export interface ResponseTransformer<T> {
}

export class JSONApiResponse<T> {
constructor(public raw: void | Response, private transformer: ResponseTransformer<T> = (jsonValue: any) => jsonValue) {}
constructor(public raw: Response, private transformer: ResponseTransformer<T> = (jsonValue: any) => jsonValue) {}

async value(): Promise<void | T> {
if (this.raw && this.raw.json) {
return this.transformer(await this.raw.json());
}
return undefined;
async value(): Promise<T> {
return this.transformer(await this.raw.json());
}
}

export class VoidApiResponse {
constructor(public raw: void | Response) {}
constructor(public raw: Response) {}

async value(): Promise<void> {
return undefined;
}
}

export class BlobApiResponse {
constructor(public raw: void | Response) {}
constructor(public raw: Response) {}

async value(): Promise<void | Blob> {
if (this.raw && this.raw.blob) {
return await this.raw.blob();
}
return undefined;
async value(): Promise<Blob> {
return await this.raw.blob();
};
}

export class TextApiResponse {
constructor(public raw: void | Response) {}
constructor(public raw: Response) {}

async value(): Promise<void | string> {
if (this.raw && this.raw.text) {
return await this.raw.text();
}
return undefined;
async value(): Promise<string> {
return await this.raw.text();
};
}
24 changes: 12 additions & 12 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -3275,7 +3275,7 @@
react-lifecycles-compat "^3.0.4"
util-deprecate "^1.0.2"

"@storybook/addon-links@^6.4.20":
"@storybook/addon-links@^6.5.9":
version "6.5.9"
resolved "https://registry.yarnpkg.com/@storybook/addon-links/-/addon-links-6.5.9.tgz#91cbca0c044796badf2498723fdd10dacea5748b"
integrity sha512-4BYC7pkxL3NLRnEgTA9jpIkObQKril+XFj1WtmY/lngF90vvK0Kc/TtvTA2/5tSgrHfxEuPevIdxMIyLJ4ejWQ==
Expand Down Expand Up @@ -4546,10 +4546,10 @@
jest-diff "^25.2.1"
pretty-format "^25.2.1"

"@types/jest@^27.5.1":
version "27.5.1"
resolved "https://registry.yarnpkg.com/@types/jest/-/jest-27.5.1.tgz#2c8b6dc6ff85c33bcd07d0b62cb3d19ddfdb3ab9"
integrity sha512-fUy7YRpT+rHXto1YlL+J9rs0uLGyiqVt3ZOTQR+4ROc47yNl8WLdVLgUloBRhOxP1PZvguHl44T3H0wAWxahYQ==
"@types/jest@^28.1.1":
version "28.1.1"
resolved "https://registry.yarnpkg.com/@types/jest/-/jest-28.1.1.tgz#8c9ba63702a11f8c386ee211280e8b68cb093cd1"
integrity sha512-C2p7yqleUKtCkVjlOur9BWVA4HgUQmEj/HWCt5WzZ5mLXrWnyIfl0wGuArc+kBXsy0ZZfLp+7dywB4HtSVYGVA==
dependencies:
jest-matcher-utils "^27.0.0"
pretty-format "^27.0.0"
Expand Down Expand Up @@ -5889,7 +5889,7 @@ babel-jest@^25.5.1:
graceful-fs "^4.2.4"
slash "^3.0.0"

babel-loader@^8.0.0, babel-loader@^8.2.4:
babel-loader@^8.0.0, babel-loader@^8.2.5:
version "8.2.5"
resolved "https://registry.yarnpkg.com/babel-loader/-/babel-loader-8.2.5.tgz#d45f585e654d5a5d90f5350a779d7647c5ed512e"
integrity sha512-OSiFfH89LrEMiWd4pLNqGz4CwJDtbs2ZVc+iGu2HrkRfPxId9F2anQj38IxWpmRfsUY0aBZYi1EFcd3mhtRMLQ==
Expand Down Expand Up @@ -12916,10 +12916,10 @@ node-fetch@^2.6.1, node-fetch@^2.6.7:
dependencies:
whatwg-url "^5.0.0"

node-fetch@^3.2.3:
version "3.2.4"
resolved "https://registry.yarnpkg.com/node-fetch/-/node-fetch-3.2.4.tgz#3fbca2d8838111048232de54cb532bd3cf134947"
integrity sha512-WvYJRN7mMyOLurFR2YpysQGuwYrJN+qrrpHjJDuKMcSPdfFccRUla/kng2mz6HWSBxJcqPbvatS6Gb4RhOzCJw==
node-fetch@^3.2.6:
version "3.2.6"
resolved "https://registry.yarnpkg.com/node-fetch/-/node-fetch-3.2.6.tgz#6d4627181697a9d9674aae0d61548e0d629b31b9"
integrity sha512-LAy/HZnLADOVkVPubaxHDft29booGglPFDr2Hw0J1AercRh01UiVFm++KMDnJeH9sHgNB4hsXPii7Sgym/sTbw==
dependencies:
data-uri-to-buffer "^4.0.0"
fetch-blob "^3.1.4"
Expand Down Expand Up @@ -16848,7 +16848,7 @@ tslib@^1.8.1, tslib@^1.9.0, tslib@^1.9.3:
resolved "https://registry.yarnpkg.com/tslib/-/tslib-1.14.1.tgz#cf2d38bdc34a134bcaf1091c41f6619e2f672d00"
integrity sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==

tslib@^2.0.0, tslib@^2.0.1, tslib@^2.0.3, tslib@^2.1.0, tslib@^2.3.1:
tslib@^2.0.0, tslib@^2.0.1, tslib@^2.0.3, tslib@^2.1.0, tslib@^2.3.1, tslib@^2.4.0:
version "2.4.0"
resolved "https://registry.yarnpkg.com/tslib/-/tslib-2.4.0.tgz#7cecaa7f073ce680a05847aa77be941098f36dc3"
integrity sha512-d6xOpEDfsi2CZVlPQzGeux8XMwLT9hssAsaPYExaQMuYskwb+x1x7J371tWlbBdWHroy99KnVB6qIkUbs5X3UQ==
Expand Down Expand Up @@ -16963,7 +16963,7 @@ typedoc-plugin-markdown@^3.12.0:
dependencies:
handlebars "^4.7.7"

typedoc@^0.22.16:
typedoc@^0.22.17:
version "0.22.17"
resolved "https://registry.yarnpkg.com/typedoc/-/typedoc-0.22.17.tgz#bc51cc95f569040112504300831cdac4f8089b7b"
integrity sha512-h6+uXHVVCPDaANzjwzdsj9aePBjZiBTpiMpBBeyh1zcN2odVsDCNajz8zyKnixF93HJeGpl34j/70yoEE5BfNg==
Expand Down

0 comments on commit d3ba4d5

Please sign in to comment.