Skip to content

Commit

Permalink
feat: adding new parameter to after middlewares
Browse files Browse the repository at this point in the history
  • Loading branch information
PaquitoSoft committed May 12, 2024
1 parent 00763c6 commit dbd4db9
Show file tree
Hide file tree
Showing 9 changed files with 5,231 additions and 11,529 deletions.
5 changes: 3 additions & 2 deletions .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,14 @@
],
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"plugin:@typescript-eslint/recommended"
],
"rules": {
"jest/no-disabled-tests": "warn",
"jest/no-focused-tests": "error",
"jest/no-identical-title": "error",
"jest/prefer-to-have-length": "warn",
"jest/valid-expect": "error"
"jest/valid-expect": "error",
"@typescript-eslint/no-non-null-assertion": "off"
}
}
16,407 changes: 5,007 additions & 11,400 deletions package-lock.json

Large diffs are not rendered by default.

8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -86,13 +86,13 @@
"cross-env": "^5.2.0",
"eslint": "^8.10.0",
"eslint-plugin-jest": "^26.1.1",
"jest": "^27.5.1",
"jest-config": "^27.5.1",
"jest": "^29.7.0",
"jest-config": "^29.7.0",
"jest-junit": "^13.0.0",
"jest-mock-extended": "^2.0.4",
"jest-unit": "0.0.1",
"lodash.camelcase": "^4.3.0",
"msw": "^0.38.1",
"msw": "^2.3.0",
"node-fetch": "^2.6.7",
"prettier": "^1.14.3",
"prompt": "^1.0.0",
Expand All @@ -108,7 +108,7 @@
"rollup-plugin-typescript2": "^0.18.0",
"shelljs": "^0.8.3",
"standard-version": "^9.3.2",
"ts-jest": "^27.1.3",
"ts-jest": "^29.1.2",
"ts-node": "^10.5.0",
"typedoc": "^0.22.12",
"typescript": "^4.6.2",
Expand Down
12 changes: 6 additions & 6 deletions setupTests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,24 @@ import fetch, { Headers } from 'node-fetch';
import { DOMParser } from 'xmldom';
import { server } from './test/mocks/server';

// @ts-ignore
// @ts-expect-error missing global declaration (TODO:)
global.fetch = fetch;
// @ts-ignore
// @ts-expect-error missing global declaration (TODO:)
global.Headers = Headers;
// @ts-ignore
// @ts-expect-error missing global declaration (TODO:)
global.DOMParser = DOMParser;

beforeAll(() => {
// Enable the mocking in tests.
server.listen()
server.listen();
});

afterEach(() => {
// Reset any runtime handlers tests may use.
server.resetHandlers()
server.resetHandlers();
});

afterAll(() => {
// Clean up once the tests are done.
server.close()
server.close();
});
12 changes: 6 additions & 6 deletions src/middleware-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,28 +6,28 @@ export type RequestMiddlewareOptions = {
fetchOptions: RequestInit;
ttl?: number; // seconds
cache?: CacheManager;
body?: any;
body?: unknown;
};

export type BeforeMiddlewaresResult = {
url: string;
fetchOptions: RequestInit;
ttl?: number;
body?: any;
body?: unknown;
};

export type BeforeMiddlewareResult = {
url?: string;
ttl?: number;
fetchOptions?: RequestInit;
body?: any;
body?: unknown;
};

export type BeforeMiddleware = (
options: RequestMiddlewareOptions
) => BeforeMiddlewareResult | undefined | null;

export type AfterMiddleware = <T>(serverData: T) => T;
export type AfterMiddleware = <T>(serverData: T, context: { response: Response }) => T;

export type Middleware = BeforeMiddleware | AfterMiddleware;

Expand Down Expand Up @@ -93,6 +93,6 @@ export function runBeforeMiddlewares({
);
}

export function runAfterMiddlewares<T>(serverData: T): T {
return middlewares.after.reduce((data, middleware) => middleware(data), serverData);
export function runAfterMiddlewares<T>(serverData: T, context: { response: Response }): T {
return middlewares.after.reduce((data, middleware) => middleware(data, context), serverData);
}
10 changes: 8 additions & 2 deletions src/send-request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ export type RequestOptions = {

const NON_CACHEABLE_HTTP_METHODS = ['POST', 'PUT', 'DELETE'];

const responsesCache = new Map<string, Response>();

function headersToObject(headers: HeadersInit): Record<string, string> {
if (headers instanceof Headers) {
return Array.from(headers.entries()).reduce<Record<string, string>>((acc, [key, value]) => {
Expand All @@ -32,6 +34,7 @@ export default async function sendRequest<T>(
url: string,
{ method = 'GET', fetchOptions, body, ttl, cache }: RequestOptions
): Promise<T> {
const responseCacheKey = `${url}__${Date.now()}`;
const headers = headersToObject(fetchOptions?.headers || {});
if (!headers['Content-Type']) {
headers['Content-Type'] = typeof body === 'string' ? 'text/plain' : 'application/json';
Expand Down Expand Up @@ -60,7 +63,9 @@ export default async function sendRequest<T>(
const cachedData = cache?.get(requestParams.url) as T;

if (cachedData) {
return Promise.resolve(runAfterMiddlewares<T>(cachedData));
return Promise.resolve(
runAfterMiddlewares<T>(cachedData, { response: responsesCache.get(responseCacheKey)! })
);
}

const response: Response = await fetch(requestParams.url, requestParams.fetchOptions);
Expand All @@ -77,7 +82,8 @@ export default async function sendRequest<T>(

if (requestParams.ttl && cache && !NON_CACHEABLE_HTTP_METHODS.includes(method)) {
cache.set(requestParams.url, data, { ttl: requestParams.ttl });
responsesCache.set(responseCacheKey, response);
}

return runAfterMiddlewares<T>(data);
return runAfterMiddlewares<T>(data, { response });
}
Loading

0 comments on commit dbd4db9

Please sign in to comment.