Skip to content

Commit

Permalink
feat: add useNileFetch hook
Browse files Browse the repository at this point in the history
BREAKING CHANGE: changed sdk interface, added *Raw functions and cancellation
  • Loading branch information
jrea committed May 11, 2022
1 parent 7d76652 commit 471a0e9
Show file tree
Hide file tree
Showing 22 changed files with 1,227 additions and 342 deletions.
6 changes: 2 additions & 4 deletions lib/nile/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
"build:readme": "./scripts/lib-readme-shim.sh",
"build:types": "tsc -d --declarationDir dist --emitDeclarationOnly",
"build:api:merge": "yarn openapi-merge-cli",
"build:api:gen": "yarn openapi-generator-cli generate -t templates -i spec/api.yaml -g typescript --package-name nile -o src/generated/openapi --additional-properties=ngVersion=6.1.7,npmName=theniledev,supportsES6=true,npmVersion=6.9.0,withInterfaces=true,withSeparateModelsAndApi=true,moduleName=Nile,projectName=@theniledev/js",
"build:api:gen": "yarn openapi-generator-cli generate -t templates -i spec/api.yaml -g typescript-fetch --package-name nile -o src/generated/openapi --additional-properties=ngVersion=6.1.7,npmName=theniledev,supportsES6=true,npmVersion=6.9.0,withInterfaces=true,withSeparateModelsAndApi=true,moduleName=Nile,typescriptThreePlus=true,projectName=@theniledev/js",
"test": "tsdx test",
"prepare": "yarn prebuild && tsdx build && yarn build:types",
"size": "size-limit",
Expand Down Expand Up @@ -68,8 +68,6 @@
"@openapitools/openapi-generator-cli": "^2.4.26",
"es6-promise": "^4.2.8",
"node-fetch": "^3.2.3",
"sade": "^1.8.1",
"url-parse": "^1.5.10",
"whatwg-fetch": "^3.6.2"
"sade": "^1.8.1"
}
}
3 changes: 2 additions & 1 deletion lib/nile/scripts/api-cleaner.sh
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#!/bin/bash

# remove login override
sed -i -e '/public login/,/}/d' ./src/generated/openapi/types/PromiseAPI.ts
sed -i -e '1,/async login/ s/async login/async delete-nile-base-login/g' ./src/generated/openapi/src/apis/DefaultApi.ts
sed -i -e '/async delete-nile-base-login/,/}/d' ./src/generated/openapi/src/apis/DefaultApi.ts
9 changes: 0 additions & 9 deletions lib/nile/scripts/lib-readme-shim.sh

This file was deleted.

37 changes: 11 additions & 26 deletions lib/nile/src/Nile.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,17 @@
/**
* the below files need generated with `yarn build:exp`
* dependencies need generated with `yarn build:api:gen`
*/
import NileApi from './generated/openapi/types/PromiseAPI';
import {
createConfiguration,
ConfigurationParameters,
} from './generated/openapi/configuration';
import { ServerConfiguration } from './generated/openapi/servers';
import {
DefaultApiRequestFactory,
DefaultApiResponseProcessor,
} from './generated/openapi/apis/DefaultApi';
import { DefaultApi } from './generated/openapi/src/';
import { Configuration } from './generated/openapi/src/runtime';

function ApiImpl(
config?: ConfigurationParameters & { apiUrl: string }
): NileApi {
const server = new ServerConfiguration<{ [key: string]: string }>(
config?.apiUrl ?? '/',
{}
);
const _config = {
baseServer: server,
...config,
};
const cfg = createConfiguration(_config);
const nileService = new DefaultApiRequestFactory(cfg);
const nileProcessor = new DefaultApiResponseProcessor();
const nile = new NileApi(cfg, nileService, nileProcessor);
type NileConfig = Configuration & { apiUrl: string };
function ApiImpl(config?: NileConfig): DefaultApi {
if (!config) {
return new DefaultApi();
}

const cfg = new Configuration({ ...config, basePath: config.apiUrl });
const nile = new DefaultApi(cfg);
return nile;
}
export default ApiImpl;
7 changes: 5 additions & 2 deletions lib/nile/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import Nile from './Nile';

export { default as NileApi } from './generated/openapi/types/PromiseAPI';
export {
DefaultApi as NileApi,
DefaultApiResults as NileApiResults,
} from './generated/openapi/src/apis/DefaultApi';

export default Nile;

export * from './generated/openapi/models/all';
export * from './generated/openapi/src/models';
134 changes: 41 additions & 93 deletions lib/nile/src/test/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,120 +1,68 @@
/* eslint-disable @typescript-eslint/ban-ts-comment */
import Nile from '..';
import { LoginInfo } from '../generated/openapi/models/LoginInfo';
import { IsomorphicFetchHttpLibrary } from '../generated/openapi/http/isomorphic-fetch';
import { LoginInfo } from '../generated/openapi/src/models/LoginInfo';

const userPayload = {
id: 4,
email: 'bob@squarepants.com',
};
jest.mock('../generated/openapi/http/isomorphic-fetch');
jest.mock('../generated/openapi/http/http', () => {
return {
RequestContext: class RequestContext {
private body: unknown;
private headers: { [key: string]: string } = {};
constructor() {
// do nothing
}

public setHeaderParam(key: string, value: string): void {
this.headers[key] = value;
}

public setBody(body: unknown) {
return (this.body = body);
}

public getBody() {
return this.body;
}

public getUrl() {
return null;
}

public getHeaders() {
return {};
}

public getHttpMethod() {
return 'GET';
}
},
HttpMethod: {
GET: 'GET',
HEAD: 'HEAD',
POST: 'POST',
PUT: 'PUT',
DELETE: 'DELETE',
CONNECT: 'CONNECT',
OPTIONS: 'OPTIONS',
TRACE: 'TRACE',
PATCH: 'PATCH',
},
};
});

describe('index', () => {
describe('login', () => {
let payload: LoginInfo;
beforeEach(() => {
payload = { email: userPayload.email, password: 'super secret' };
// @ts-expect-error
IsomorphicFetchHttpLibrary.mockReset();
global.fetch = jest.fn(() =>
Promise.resolve({
json: () => Promise.resolve({ rates: { CAD: 1.42 } }),
})
);
});
afterEach(() => {
// @ts-expect-error
fetch.mockClear();
});

it('works', async () => {
// @ts-expect-error
IsomorphicFetchHttpLibrary.mockImplementation(() => {
return {
send: () => {
return {
toPromise: () => {
return {
httpStatusCode: 200,
headers: { 'content-type': 'application/json' },
body: {
text: () => {
return JSON.stringify({ token: 'password123' });
},
},
};
},
};
},
};
});
fetch.mockImplementation(() => ({
status: 200,
json: () => Promise.resolve({ token: 123 }),
}));
const nile = Nile();
await nile.login(payload);
expect(nile.authToken).not.toBeNull();
await nile.login({ loginInfo: payload });
expect(nile.authToken).toBeTruthy();
});

it('does not work', async () => {
// @ts-expect-error
IsomorphicFetchHttpLibrary.mockImplementation(() => {
return {
send: () => {
return {
toPromise: () => {
return {
httpStatusCode: 200,
headers: { 'content-type': 'application/json' },
body: {
text: () => {
return JSON.stringify({});
},
},
};
},
};
},
};
});

fetch.mockImplementation(() => ({
status: 200,
json: () => Promise.resolve({}),
}));
const nile = Nile();
await nile.login({ loginInfo: payload });

expect(nile.authToken).toBeFalsy();
});

await nile.login(payload);
it('cancels', async () => {
const abortSpy = jest.spyOn(AbortController.prototype, 'abort');
// eat the warning, we're gonna make it happen
jest.spyOn(console, 'warn').mockImplementation(() => null);

const json = jest.fn();

// @ts-expect-error
fetch.mockImplementation(() => ({
status: 200,
json,
}));
const nile = Nile();
const request = nile.loginRaw({ loginInfo: payload });
request.controller.abort();
expect(abortSpy).toBeCalled();
expect(json).not.toBeCalled();
expect(nile.authToken).toBeFalsy();
});
});
Expand Down

0 comments on commit 471a0e9

Please sign in to comment.