Skip to content
Open
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
3,708 changes: 2,105 additions & 1,603 deletions package-lock.json

Large diffs are not rendered by default.

17 changes: 12 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,16 @@
"name": "@sagacify/api-reader",
"version": "2.2.0",
"description": "REST API request handler",
"main": "build/NodeApiReader.js",
"browser": "build/BrowserApiReader.js",
"exports": "./build/NodeApiReader.js",
"browser": "./build/BrowserApiReader.js",
"directories": {
"lib": "build/src",
"test": "build/test"
},
"type": "module",
"engines": {
"node": "^12.20.0 || >=14.13.1"
},
"bugs": {
"url": "https://github.com/Sagacify/autoroute/issues"
},
Expand All @@ -34,17 +38,18 @@
"lint": "eslint --fix ./src ./test",
"test:lint": "eslint -f stylish ./src ./test",
"test:types": "tsc --noEmit --skipLibCheck",
"test:spec": "env NODE_ENV=test mocha .",
"test:spec": "env NODE_ENV=test ts-mocha .",
"test:cover": "nyc npm run test:spec",
"test:watch": "env NODE_ENV=test mocha --watch",
"test": "npm run test:lint && npm run test:types && npm run test:cover"
},
"dependencies": {
"node-fetch": "^3.1.0",
"qs": "^6.10.2"
"node-fetch": "^3.2.3",
"qs": "^6.10.3"
},
"devDependencies": {
"@sagacify/eslint-config": "^1.2.0",
"@tsconfig/node12": "^1.0.9",
"@types/chai": "^4.3.0",
"@types/mocha": "^9.0.0",
"@types/node": "^17.0.0",
Expand All @@ -64,6 +69,7 @@
"nyc": "^15.1.0",
"prettier": "^2.5.1",
"sinon": "^12.0.1",
"ts-mocha": "^9.0.2",
"ts-node": "^10.4.0",
"typescript": "^4.5.4"
},
Expand All @@ -86,6 +92,7 @@
}
},
"mocha": {
"loader": "ts-node/esm",
"require": "ts-node/register",
"spec": [
"test/**/*.ts"
Expand Down
24 changes: 13 additions & 11 deletions src/BrowserApiReader.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
/* global fetch, Headers, btoa */
import { IsoApiReader, ApiReaderOptions } from './IsoApiReader';

const { IsoApiReader } = require('./IsoApiReader');

module.exports.ApiReader = class ApiReader extends IsoApiReader {
constructor (baseUrl, options) {
super(baseUrl, options, {
fetch,
Headers,
btoa
});
export class ApiReader extends IsoApiReader {
constructor(baseUrl: string, options: ApiReaderOptions) {
super(
{
fetch: window.fetch,
Headers: window.Headers,
btoa: window.btoa
},
baseUrl,
options
);
}
};
}
79 changes: 44 additions & 35 deletions src/IsoApiReader.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,25 @@
import qs from 'qs';
import nFetch, { Headers as nHeaders, BodyInit as nBodyInit } from 'node-fetch';
import * as qs from 'qs';
import type {
Headers as nHeaders,
BodyInit as nBodyInit,
RequestInit as nRequestInit
} from 'node-fetch';
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I now, this is only a lint change but we should import types here instead of the objects.


type IsoHeadersClass = typeof Headers | typeof nHeaders;
type IsoHeaders = Headers | nHeaders;
type IsoBody = BodyInit | nBodyInit | null;
type IsoRequestInit = RequestInit | nRequestInit;

function isNodeBody(input: IsoBody): input is nBodyInit {
return (input as any)?.buffer !== undefined;
// Special types for handlers, JSON is still not stringified
export interface IsoPreRequestInit
extends Omit<nRequestInit | IsoRequestInit, 'body'> {
body?: BodyInit | Record<string, unknown> | null;
}

// function test(input: IsoBody): void {
// if (isNodeBody(input)) {
// input.body
// }
// }

type IsoFetchOptions = {
method: string;
headers: IsoHeaders;
body?: IsoBody;
};

type IsoFetch = typeof fetch | typeof nFetch;
export type IsoFetch = (
url: RequestInfo,
init?: IsoRequestInit
) => Promise<Response>;

type SimpleRequest = {
url: string;
Expand All @@ -36,7 +34,7 @@ type SimpleResponse = {
ok: boolean;
redirected: boolean;
type: string;
headers: object;
headers: Record<string, unknown>;
body: unknown;
};

Expand All @@ -45,7 +43,7 @@ type Auth = {
password?: string;
};

type PreRequestHandler = (options: IsoFetchOptions) => IsoFetchOptions;
type PreRequestHandler = (options: IsoPreRequestInit) => IsoPreRequestInit;
type HttpErrorHandler = (req: SimpleRequest, res: SimpleResponse) => void;

export type ApiReaderOptions = {
Expand All @@ -69,7 +67,7 @@ type ReqOptions = {
method?: string;
headers?: Record<string, string>;
query?: Record<string, unknown>;
body?: (BodyInit & nBodyInit) | null;
body?: (BodyInit & nBodyInit) | Record<string, unknown> | null;
auth?: Auth;
json?: boolean;
};
Expand Down Expand Up @@ -130,7 +128,7 @@ export class IsoApiReader {
}

mergeHeaders(baseHeaders: IsoHeaders, newHeaders: IsoHeaders): IsoHeaders {
const finalHeaders = new this.Headers(baseHeaders);
const finalHeaders = new this.Headers(baseHeaders as nHeaders);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here you force the type to be nHeaders, but how do you know what got ?


newHeaders.forEach((name, value) => {
finalHeaders.set(name, value);
Expand All @@ -151,7 +149,7 @@ export class IsoApiReader {
url.pathname = `${url.pathname}/${path}`.replace(/\/+/, '/');
const reqHeaders = new this.Headers(headers);

let fetchOptions: IsoFetchOptions = {
let fetchOptions: IsoPreRequestInit = {
method: method.toUpperCase(),
headers: this.mergeHeaders(this.baseHeaders, reqHeaders)
};
Expand All @@ -161,7 +159,7 @@ export class IsoApiReader {
if (finalAuth) {
const { username, password } = finalAuth;

fetchOptions.headers.set(
(fetchOptions.headers as IsoHeaders).set(
'Authorization',
`Basic ${btoa(`${username || ''}:${password || ''}`)}`
);
Expand All @@ -172,21 +170,30 @@ export class IsoApiReader {
}

if (this.preRequestHandler) {
fetchOptions = this.preRequestHandler({ ...fetchOptions, body });
fetchOptions = this.preRequestHandler({
...(fetchOptions as IsoRequestInit),
body
});
}

if (body !== undefined) {
const finalJson = json !== undefined ? json : this.json;

if (finalJson) {
fetchOptions.headers.set('Content-Type', 'application/json');
(fetchOptions.headers as IsoHeaders).set(
'Content-Type',
'application/json'
);
fetchOptions.body = JSON.stringify(body);
} else {
fetchOptions.body = body;
}
}

const fetchRes = await fetch(url.toString(), fetchOptions);
const fetchRes = await fetch(
url.toString(),
fetchOptions as IsoRequestInit
);
const contentType = (fetchRes.headers.get('Content-Type') || '')
.split(';', 1)[0]
.toLocaleLowerCase()
Expand Down Expand Up @@ -222,9 +229,11 @@ export class IsoApiReader {

const req = {
url: url.toString(),
method: fetchOptions.method,
headers: IsoApiReader.headersToObject(fetchOptions.headers),
body: fetchOptions.body
method: fetchOptions.method as string,
headers: IsoApiReader.headersToObject(
fetchOptions.headers as IsoHeaders
),
body: fetchOptions.body as IsoBody
};

return this.httpErrorHandler(req, res);
Expand All @@ -233,27 +242,27 @@ export class IsoApiReader {
return resBody;
}

async head(path: string, options: DefniedReqOptions) {
async head(path: string, options: DefniedReqOptions = {}) {
return this.req(path, { ...options, method: 'HEAD' });
}

async get(path: string, options: DefniedReqOptions) {
async get(path: string, options: DefniedReqOptions = {}) {
return this.req(path, { ...options, method: 'GET' });
}

async post(path: string, options: DefniedReqOptions) {
async post(path: string, options: DefniedReqOptions = {}) {
return this.req(path, { ...options, method: 'POST' });
}

async put(path: string, options: DefniedReqOptions) {
async put(path: string, options: DefniedReqOptions = {}) {
return this.req(path, { ...options, method: 'PUT' });
}

async patch(path: string, options: DefniedReqOptions) {
async patch(path: string, options: DefniedReqOptions = {}) {
return this.req(path, { ...options, method: 'PATCH' });
}

async delete(path: string, options: DefniedReqOptions) {
async delete(path: string, options: DefniedReqOptions = {}) {
return this.req(path, { ...options, method: 'DELETE' });
}
}
18 changes: 14 additions & 4 deletions src/NodeApiReader.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,24 @@
import { IsoApiReader, ApiReaderOptions } from './IsoApiReader';
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import { IsoApiReader, ApiReaderOptions, IsoFetch } from './IsoApiReader.ts';
// Add missing NodeJS classes/functions
import nFetch, { Headers as nHeaders } from 'node-fetch';

import {
Headers as nHeaders,
RequestInfo,
RequestInit,
Response
} from 'node-fetch';
const nFetch = (url: RequestInfo, init?: RequestInit): Promise<Response> =>
import('node-fetch').then(({ default: fetch }) => fetch(url, init));

const nBtoa = (text: string) => Buffer.from(text).toString('base64');

export class ApiReader extends IsoApiReader {
constructor(baseUrl: string, options: ApiReaderOptions) {
constructor(baseUrl: string, options: ApiReaderOptions = {}) {
super(
{
fetch: nFetch,
fetch: nFetch as unknown as IsoFetch,
Headers: nHeaders,
btoa: nBtoa
},
Expand Down
Loading