@servicetitan/ajax-handlers
Advanced tools
Comparing version 23.3.0 to 23.4.0
@@ -1,2 +0,2 @@ | ||
export declare const worker: import("msw/lib/glossary-de6278a9").b; | ||
export declare const worker: import("msw/browser").SetupWorker; | ||
//# sourceMappingURL=browser.d.ts.map |
@@ -1,4 +0,4 @@ | ||
import { setupWorker } from 'msw'; | ||
import { setupWorker } from 'msw/browser'; | ||
import { handlers } from './handlers'; | ||
export const worker = setupWorker(...handlers); | ||
//# sourceMappingURL=browser.js.map |
@@ -1,11 +0,2 @@ | ||
import { AsyncResponseResolverReturnType, MockedResponse, ResponseComposition, RestContext, RestRequest } from 'msw'; | ||
export interface RequestCountsData { | ||
requestCounts: { | ||
[key: string]: number; | ||
}; | ||
} | ||
export declare function withRequestCount(resolver: (req: RestRequest, res: ResponseComposition, ctx: RestContext, requestCounts: { | ||
[key: string]: number; | ||
}) => AsyncResponseResolverReturnType<MockedResponse>): (req: RestRequest, res: ResponseComposition, ctx: RestContext) => AsyncResponseResolverReturnType<MockedResponse<any>>; | ||
export declare const handlers: import("msw").RestHandler<import("msw/lib/glossary-de6278a9").M<import("msw/lib/glossary-de6278a9").h>>[]; | ||
export declare const handlers: import("msw/lib/core/handlers/HttpHandler").HttpHandler[]; | ||
//# sourceMappingURL=handlers.d.ts.map |
@@ -1,53 +0,48 @@ | ||
import { rest, } from 'msw'; | ||
// Higher order function to keep track of request counts in session storage | ||
export function withRequestCount(resolver) { | ||
return (req, res, ctx) => { | ||
var _a, _b; | ||
const path = req.url.pathname; | ||
const requestCounts = JSON.parse((_a = sessionStorage.getItem('requestCounts')) !== null && _a !== void 0 ? _a : '{}'); | ||
const requestCount = (_b = requestCounts[path]) !== null && _b !== void 0 ? _b : 0; | ||
const newCountsObj = Object.assign(Object.assign({}, requestCounts), { [path]: requestCount + 1 }); | ||
sessionStorage.setItem('requestCounts', JSON.stringify(newCountsObj)); | ||
return resolver(req, res, ctx, newCountsObj); | ||
}; | ||
} | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
return new (P || (P = Promise))(function (resolve, reject) { | ||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
}; | ||
import { HttpResponse, delay, http } from 'msw'; | ||
// Higher order function to add delay to a response if present in search params | ||
function withDelay(resolver) { | ||
return (req, res, ctx) => { | ||
const delay = req.url.searchParams.get('delay'); | ||
if (delay) { | ||
const resWithDelay = (...params) => res(ctx.delay(Number(delay)), ...params); | ||
return resolver(req, resWithDelay, ctx); | ||
return (info) => __awaiter(this, void 0, void 0, function* () { | ||
const delayVal = new URL(info.request.url).searchParams.get('delay'); | ||
if (delayVal) { | ||
yield delay(Number(delayVal)); | ||
} | ||
return resolver(req, res, ctx); | ||
}; | ||
return resolver(info); | ||
}); | ||
} | ||
export const handlers = [ | ||
// Get auth token set to :username | ||
rest.get('/refresh_token/:username', withDelay(withRequestCount((req, res, ctx, _requestCounts) => { | ||
const { username } = req.params; | ||
return res(ctx.status(200), ctx.body(username)); | ||
}))), | ||
rest.get('/user', withDelay(withRequestCount((req, res, ctx, requestCounts) => { | ||
http.get('/refresh_token/:username', withDelay(({ params }) => { | ||
const { username } = params; | ||
return HttpResponse.text(String(username)); | ||
})), | ||
http.get('/user', withDelay(({ request }) => { | ||
var _a, _b; | ||
const token = (_b = (_a = req.headers.get('Authorization')) === null || _a === void 0 ? void 0 : _a.split(' ')[1]) !== null && _b !== void 0 ? _b : ''; | ||
const token = (_b = (_a = request.headers.get('Authorization')) === null || _a === void 0 ? void 0 : _a.split(' ')[1]) !== null && _b !== void 0 ? _b : ''; | ||
if (!token) { | ||
// If not authenticated, respond with a 401 error | ||
return res(ctx.status(401), ctx.json({ | ||
return HttpResponse.json({ | ||
errorMessage: 'Unauthorized', | ||
})); | ||
}, { status: 401 }); | ||
} | ||
// If authenticated, return a mocked user details | ||
return res(ctx.status(200), ctx.json({ | ||
return HttpResponse.json({ | ||
username: token, | ||
requestCounts, | ||
})); | ||
}))), | ||
rest.get('/public', (req, res, ctx) => { | ||
return res(ctx.status(200)); | ||
}); | ||
})), | ||
http.get('/public', () => { | ||
return HttpResponse.text('200'); | ||
}), | ||
rest.get('/broken', (req, res) => { | ||
return res.networkError('Failed to connect'); | ||
http.get('/broken', () => { | ||
return HttpResponse.error(); | ||
}), | ||
]; | ||
//# sourceMappingURL=handlers.js.map |
@@ -1,2 +0,2 @@ | ||
export declare const server: import("msw/lib/glossary-de6278a9").K; | ||
export declare const server: import("msw/node").SetupServerApi; | ||
//# sourceMappingURL=server.d.ts.map |
@@ -23,3 +23,3 @@ import axios from 'axios'; | ||
} | ||
throw 'Incorrect date format'; | ||
throw new Error('Incorrect date format'); | ||
} | ||
@@ -26,0 +26,0 @@ return date; |
@@ -15,3 +15,3 @@ import axios from 'axios'; | ||
status: request.status, | ||
requestUrl: config.url, | ||
requestUrl: config === null || config === void 0 ? void 0 : config.url, | ||
readyState: request.readyState, | ||
@@ -18,0 +18,0 @@ }, |
{ | ||
"name": "@servicetitan/ajax-handlers", | ||
"version": "23.3.0", | ||
"version": "23.4.0", | ||
"description": "", | ||
@@ -21,13 +21,13 @@ "repository": { | ||
"devDependencies": { | ||
"@servicetitan/react-ioc": "23.3.0", | ||
"@servicetitan/react-ioc": "23.4.0", | ||
"@testing-library/jest-dom": "^6.4.2", | ||
"@testing-library/react": "^14.2.1", | ||
"@testing-library/react": "^14.2.2", | ||
"@types/js-cookie": "~3.0.3", | ||
"axios": "~0.27.2", | ||
"msw": "^1.3.1", | ||
"axios": "~0.28.0", | ||
"msw": "^2.2.13", | ||
"react": "~18.2.0" | ||
}, | ||
"peerDependencies": { | ||
"@servicetitan/react-ioc": "23.3.0", | ||
"axios": "~0.27.2", | ||
"@servicetitan/react-ioc": "23.4.0", | ||
"axios": "~0.28.0", | ||
"react": ">=17.0.2" | ||
@@ -41,3 +41,3 @@ }, | ||
}, | ||
"gitHead": "4a3420cf55cf34ff10b5ba6164d940b39f0925e6" | ||
"gitHead": "94612136ff4d645bc38ae6b13fffad2ab0358666" | ||
} |
@@ -1,4 +0,4 @@ | ||
import { setupWorker } from 'msw'; | ||
import { setupWorker } from 'msw/browser'; | ||
import { handlers } from './handlers'; | ||
export const worker = setupWorker(...handlers); |
@@ -1,53 +0,12 @@ | ||
import { | ||
AsyncResponseResolverReturnType, | ||
MockedResponse, | ||
ResponseComposition, | ||
rest, | ||
RestContext, | ||
RestRequest, | ||
} from 'msw'; | ||
import { HttpResponse, delay, http, HttpResponseResolver } from 'msw'; | ||
export interface RequestCountsData { | ||
requestCounts: { [key: string]: number }; | ||
} | ||
// Higher order function to keep track of request counts in session storage | ||
export function withRequestCount( | ||
resolver: ( | ||
req: RestRequest, | ||
res: ResponseComposition, | ||
ctx: RestContext, | ||
requestCounts: { [key: string]: number } | ||
) => AsyncResponseResolverReturnType<MockedResponse> | ||
) { | ||
return (req: RestRequest, res: ResponseComposition, ctx: RestContext) => { | ||
const path = req.url.pathname; | ||
const requestCounts = JSON.parse(sessionStorage.getItem('requestCounts') ?? '{}'); | ||
const requestCount: number = requestCounts[path] ?? 0; | ||
const newCountsObj = { ...requestCounts, [path]: requestCount + 1 }; | ||
sessionStorage.setItem('requestCounts', JSON.stringify(newCountsObj)); | ||
return resolver(req, res, ctx, newCountsObj); | ||
}; | ||
} | ||
// Higher order function to add delay to a response if present in search params | ||
function withDelay( | ||
resolver: ( | ||
req: RestRequest, | ||
res: | ||
| ResponseComposition | ||
| ((...params: Parameters<ResponseComposition>) => ReturnType<ResponseComposition>), | ||
ctx: RestContext | ||
) => AsyncResponseResolverReturnType<MockedResponse> | ||
) { | ||
return (req: RestRequest, res: ResponseComposition, ctx: RestContext) => { | ||
const delay = req.url.searchParams.get('delay'); | ||
if (delay) { | ||
const resWithDelay = (...params: Parameters<ResponseComposition>) => | ||
res(ctx.delay(Number(delay)), ...params); | ||
return resolver(req, resWithDelay, ctx); | ||
function withDelay(resolver: HttpResponseResolver) { | ||
return async (info: Parameters<HttpResponseResolver>[0]) => { | ||
const delayVal = new URL(info.request.url).searchParams.get('delay'); | ||
if (delayVal) { | ||
await delay(Number(delayVal)); | ||
} | ||
return resolver(req, res, ctx); | ||
return resolver(info); | ||
}; | ||
@@ -58,46 +17,38 @@ } | ||
// Get auth token set to :username | ||
rest.get( | ||
http.get( | ||
'/refresh_token/:username', | ||
withDelay( | ||
withRequestCount((req, res, ctx, _requestCounts) => { | ||
const { username } = req.params; | ||
return res(ctx.status(200), ctx.body(username as string)); | ||
}) | ||
) | ||
withDelay(({ params }) => { | ||
const { username } = params; | ||
return HttpResponse.text(String(username)); | ||
}) | ||
), | ||
rest.get( | ||
http.get( | ||
'/user', | ||
withDelay( | ||
withRequestCount((req, res, ctx, requestCounts) => { | ||
const token = req.headers.get('Authorization')?.split(' ')[1] ?? ''; | ||
if (!token) { | ||
// If not authenticated, respond with a 401 error | ||
return res( | ||
ctx.status(401), | ||
ctx.json({ | ||
errorMessage: 'Unauthorized', | ||
}) | ||
); | ||
} | ||
withDelay(({ request }) => { | ||
const token = request.headers.get('Authorization')?.split(' ')[1] ?? ''; | ||
if (!token) { | ||
// If not authenticated, respond with a 401 error | ||
return HttpResponse.json( | ||
{ | ||
errorMessage: 'Unauthorized', | ||
}, | ||
{ status: 401 } | ||
); | ||
} | ||
// If authenticated, return a mocked user details | ||
return res( | ||
ctx.status(200), | ||
ctx.json({ | ||
username: token, | ||
requestCounts, | ||
}) | ||
); | ||
}) | ||
) | ||
// If authenticated, return a mocked user details | ||
return HttpResponse.json({ | ||
username: token, | ||
}); | ||
}) | ||
), | ||
rest.get('/public', (req, res, ctx) => { | ||
return res(ctx.status(200)); | ||
http.get('/public', () => { | ||
return HttpResponse.text('200'); | ||
}), | ||
rest.get('/broken', (req, res) => { | ||
return res.networkError('Failed to connect'); | ||
http.get('/broken', () => { | ||
return HttpResponse.error(); | ||
}), | ||
]; |
@@ -1,2 +0,2 @@ | ||
import axios, { AxiosRequestTransformer, AxiosRequestHeaders } from 'axios'; | ||
import axios, { AxiosRequestHeaders, AxiosResponseTransformer } from 'axios'; | ||
import Cookies from 'js-cookie'; | ||
@@ -29,3 +29,3 @@ | ||
throw 'Incorrect date format'; | ||
throw new Error('Incorrect date format'); | ||
} | ||
@@ -37,3 +37,3 @@ | ||
export const initAjaxHandlersCommon = () => { | ||
const transformer: AxiosRequestTransformer = data => { | ||
const transformer: AxiosResponseTransformer = data => { | ||
if (typeof data === 'string') { | ||
@@ -40,0 +40,0 @@ return dateFromString(data); |
@@ -23,3 +23,3 @@ import axios, { AxiosError } from 'axios'; | ||
status: request.status, | ||
requestUrl: config.url, | ||
requestUrl: config?.url, | ||
readyState: request.readyState, | ||
@@ -26,0 +26,0 @@ }, |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
120008
2295