A NestJS microservice in front of the SellerMagnet API validates every request with a class-validator DTO before it can spend a credit, answers repeat lookups from a short-lived in-process cache, and retries only the status codes a second attempt can fix. This guide builds that wrapper - lookup.dto.ts, cache.service.ts, lookup.controller.ts and app.module.ts are new, and the TypeScript quickstart's own sellermagnet.ts and retry.ts are reused unchanged - and tests all of it against a fails-closed fake HTTP layer so nothing here is just described.
Key Takeaways
- Two small class-validator DTOs (
AsinParamDto,MarketplaceQueryDto) run through Nest's globalValidationPipebefore the controller body, so a bad request costs nothing and waits on no timeout. - A small in-process
CacheService(a plain Map) answers a repeated lookup for free; it lives in one Nest process, so several PM2 cluster workers or container replicas each keep their own copy unless you add a shared store. - The retry policy is the quickstart's own: 429 waits for free, a 500 is retried once (it is refunded), 502/503 are retried up to 4 times (each billed), and a 404 is a real answer, never retried.
- sellermagnet.ts and retry.ts do not change between a Vitest mock-testing suite and a NestJS controller: the same fetch-based client works in both, with ONE mechanical adaptation documented below.
- A plain fetch failure (DNS, refused connection, our own AbortSignal timeout) throws a TypeError, not an ApiError - retry.ts's getWithRetry only retries ApiError instances, so a dropped connection reaches the controller after exactly one attempt, with nothing billed.
Why validate with DTOs instead of checking fields by hand in the controller?
NestJS's ValidationPipe runs class-validator decorators against the incoming @Param() and @Query() objects before the controller method body ever executes, so a malformed ASIN or an unknown marketplace ID never opens a connection to the upstream API: it fails with a 400 at the pipe, not inside the handler. Keeping the asin and marketplaceId checks as two small DTOs rather than one shared schema matches how Nest actually receives them - a path parameter and a query parameter are two different sources, validated by two different pipes. The full list of all 23 marketplace IDs is in the marketplace IDs list; this wrapper's MARKETPLACE_IDS covers four of them.
Dependencies
npm install @nestjs/core @nestjs/common @nestjs/platform-express class-validator class-transformer reflect-metadata
export SELLERMAGNET_API_KEY="your-key-here"
How do I validate the ASIN and marketplace before spending a credit?
AsinParamDto normalizes a lower-case ASIN to upper case with a @Transform decorator before @Matches checks the shape, so a request for b0cl61f39h is accepted and normalized, while short is rejected outright. MarketplaceQueryDto's @IsIn check is a plain membership test against the known marketplace IDs. Neither DTO needs a hand-rolled validator function: Nest's ValidationPipe (configured with transform: true, whitelist: true in main.ts) applies both automatically to every request, before any network call.
lookup.dto.ts - class-validator DTOs, checked before any network call
// lookup.dto.ts - class-validator DTOs that fail closed before any network
// call. Two sources (a path param and a query param) get their own small
// DTO rather than one merged shape, since Nest validates @Param() and
// @Query() as separate pipes.
import { IsIn, Matches } from "class-validator";
import { Transform } from "class-transformer";
const ASIN_RE = /^[A-Z0-9]{10}$/;
// The handful of marketplace IDs covered by this wrapper; the full list of
// all 23 is in https://sellermagnet-api.com/blog/amazon-marketplace-ids-list
export const MARKETPLACE_IDS = [
"ATVPDKIKX0DER", // amazon.com
"A1PA6795UKMFR9", // amazon.de
"A1F83G8C2ARO7P", // amazon.co.uk
"A13V1IB3VIYZZH", // amazon.fr
] as const;
export class AsinParamDto {
@Transform(({ value }) => (typeof value === "string" ? value.trim().toUpperCase() : value))
@Matches(ASIN_RE, { message: "asin must be 10 upper-case letters/digits" })
asin!: string;
}
export class MarketplaceQueryDto {
@IsIn(MARKETPLACE_IDS, { message: `marketplaceId must be one of ${MARKETPLACE_IDS.join(", ")}` })
marketplaceId!: string;
}
How does the cache avoid paying twice for the same ASIN?
CacheService wraps a plain Map keyed by asin:marketplaceId, with each entry carrying its own expiry, registered as a Nest provider with a useFactory so the 300 second TTL is set in one place (app.module.ts). A lookup within the TTL returns the stored result with cached: true and makes no network call at all; a lookup after the TTL, or for a key never seen, falls through to the upstream call and refreshes the entry. This cache lives in the process that holds it: running the service under PM2 in cluster mode (or behind several container replicas) means each worker keeps its own copy, so the same ASIN can still be fetched once per worker. That trade-off is deliberate here - a shared cache needs an external store a reader picks for their own deployment, which this post does not assume or name.
cache.service.ts - a per-process TTL cache, registered as a Nest provider
// cache.service.ts - a tiny in-process TTL cache, keyed by
// "asin:marketplaceId".
//
// Not a cross-process cache (no external cache store named here, by the
// owner's infrastructure rule): one Nest process holds its own Map. A
// reader running the service behind PM2 cluster mode or several container
// replicas needs a shared store of their own choice; that trade-off is
// called out in the post, not hidden.
import { Injectable } from "@nestjs/common";
interface Entry<V> {
expiresAt: number;
value: V;
}
@Injectable()
export class CacheService<V = unknown> {
private readonly ttlMs: number;
private readonly store = new Map<string, Entry<V>>();
constructor(ttlMs = 300_000) {
this.ttlMs = ttlMs;
}
get(key: string): V | undefined {
const hit = this.store.get(key);
if (!hit) return undefined;
if (hit.expiresAt < Date.now()) {
this.store.delete(key);
return undefined;
}
return hit.value;
}
set(key: string, value: V): void {
this.store.set(key, { expiresAt: Date.now() + this.ttlMs, value });
}
get size(): number {
return this.store.size;
}
}
What does the NestJS controller itself look like?
The global ValidationPipe has already rejected a bad request by the time getLookup runs, so the handler only has to check the cache and then call getWithRetry around the quickstart's own raw lookup endpoint. retry.ts's getWithRetry<T> is generic over the raw JSON shape it fetches, not over sellermagnet.ts's already-decoded ProductInfo (that file's own lookup() calls the un-retried get() directly, never through getWithRetry), so this controller retries the same raw productInfo envelope lookup() would decode, and applies the same "N/A" to null price decode inline, rather than reimplementing lookup() itself behind a retry it was never given. A plain fetch failure - the connection was refused, DNS failed, or our own AbortSignal fired after 120 seconds - surfaces as a TypeError, not an ApiError: getWithRetry only retries ApiError instances, so that branch needs its own handling, or a dropped connection reaches the client as an unhandled 500 instead of the wrapper's own 502.
lookup.controller.ts - the NestJS route
// lookup.controller.ts - the NestJS route wrapping the SellerMagnet API's
// product lookup.
//
// Nest's ValidationPipe (lookup.dto.ts) rejects a bad asin or marketplaceId
// with a 400 before the handler body runs, so no network call is ever made
// for a malformed request. A cache hit (cache.service.ts) also answers
// before the upstream call. Only a validated, uncached request reaches
// getWithRetry() + lookup(), reused unchanged from the TypeScript quickstart.
import { Controller, Get, Param, Query, HttpException, HttpStatus } from "@nestjs/common";
import { CacheService } from "./cache.service";
import { ApiError } from "./sellermagnet";
import { getWithRetry } from "./retry";
import { AsinParamDto, MarketplaceQueryDto } from "./lookup.dto";
export interface LookupResult {
asin: string;
title: string;
price: number | null;
currency: string | null;
cached: boolean;
}
// retry.ts's getWithRetry<T> is generic over the raw JSON shape, not over
// sellermagnet.ts's decoded ProductInfo (lookup() in that file calls the
// un-retried get() directly) - so the retried call here targets the same
// raw productInfo envelope lookup() decodes, and this controller applies
// the same "N/A" -> null decode lookup() does, inline, rather than
// reimplementing lookup() itself behind a retry it was never given.
interface RawLookupResponse {
productInfo: {
asin: string;
title: string;
buyBoxInfo: { price: number | "N/A"; currencyCode: string };
};
}
@Controller()
export class LookupController {
constructor(private readonly cache: CacheService<LookupResult>) {}
@Get("lookup/:asin")
async getLookup(@Param() params: AsinParamDto, @Query() query: MarketplaceQueryDto): Promise<LookupResult> {
const { asin } = params;
const { marketplaceId } = query;
const cacheKey = `${asin}:${marketplaceId}`;
const cached = this.cache.get(cacheKey);
if (cached !== undefined) {
return { ...cached, cached: true };
}
let raw: RawLookupResponse;
try {
raw = await getWithRetry<RawLookupResponse>("amazon-product-lookup", { asin, marketplaceId });
} catch (err) {
if (err instanceof ApiError) {
if (err.status === 404) {
throw new HttpException("asin not found on this marketplace", HttpStatus.NOT_FOUND);
}
throw new HttpException("upstream lookup failed", HttpStatus.BAD_GATEWAY);
}
// a plain fetch/network failure (DNS, refused connection, our own
// AbortSignal firing after 120s) is not an ApiError - it never got an
// HTTP response at all, so it needs its own branch next to ApiError,
// or it reaches the client as an unhandled 500 instead of this
// wrapper's 502.
throw new HttpException("upstream unreachable", HttpStatus.BAD_GATEWAY);
}
const info = raw.productInfo;
const result: LookupResult = {
asin: info.asin,
title: info.title,
price: typeof info.buyBoxInfo.price === "number" ? info.buyBoxInfo.price : null, // never 0
currency: info.buyBoxInfo.currencyCode ?? null,
cached: false,
};
this.cache.set(cacheKey, result);
return result;
}
}
app.module.ts - wiring the controller and the cache provider
// app.module.ts - NestJS module wiring: the lookup controller plus one
// CacheService instance, shared across requests in this process.
import { Module } from "@nestjs/common";
import { LookupController } from "./lookup.controller";
import { CacheService } from "./cache.service";
@Module({
controllers: [LookupController],
providers: [
{
provide: CacheService,
useFactory: () => new CacheService(300_000), // 300s, one per process
},
],
})
export class AppModule {}
A client timeout is not the same as a free connection error
The plain-fetch-failure branch above only ever fires when the request never reached the server at all (DNS failure, refused connection), so nothing was billed. The quickstart's own AbortSignal.timeout(120_000) firing is different in one way that matters for billing on some upstream failure modes: if the server had already started processing before the connection dropped, the credit can already be deducted and is not refunded. Keep the client timeout at 120 seconds, matching the server, rather than cutting it short to "fail fast".

Trimmed response for a cache-miss lookup
{
"asin": "B0CL61F39H",
"title": "PlayStation\u00ae5 console (slim)",
"price": 444.99,
"currency": "USD",
"cached": false
}
| Scenario | HTTP status | Retried? | Billed? |
|---|---|---|---|
| Valid ASIN, cache miss | 200 | - | Yes (1 credit) |
| Same lookup again within 300s | 200 (cached) | no | No - 0 upstream calls |
| Malformed ASIN shape | 400 | no | No - rejected before the network |
| Unknown marketplaceId | 400 | no | No - rejected before the network |
| Lower-case ASIN, cache miss | 200 | - | Yes - DTO transform normalizes it first |
| No featured offer (price "N/A") | 200 | - | Yes - decodes to null, not 0 |
| Upstream 404 (not on this marketplace) | 404 | no | Yes - a real answer |
| Upstream 429 (concurrency cap) | 200 (after a wait) | yes - free | No - the 429 itself |
| Upstream 500 (refunded) | 200 (after 1 retry) | yes, capped at 1 | No - the 500 itself |
| Two upstream 500s in a row | 502 | no - stops | No - the 500s |
| Upstream 502 / 503 | 502 | yes, up to 4 attempts | Yes - every attempt |
| Connection error (never reached the server) | 502 | no - not an ApiError | No - nothing was billed |

Why fake globalThis.fetch instead of the HTTP transport underneath it?
mockFetch.ts, reused unchanged from the TypeScript mock-testing guide, replaces globalThis.fetch itself - typed as typeof fetch, so a drift from the real fetch signature is a compile error - rather than faking the HTTP transport one layer below it. That distinction is not cosmetic: a library that only patches the Node http/https module, or only swaps the transport's global dispatcher, does not reliably intercept Node's native fetch on every Node build. Both were tried while building this post: with that kind of interception active and net connect disabled, a test lookup still reached the real sellermagnet-api.com and came back with a genuine 401. Replacing globalThis.fetch itself has no such gap, because it swaps the function the client calls directly.
mockFetch.ts - fakes only globalThis.fetch, typed as typeof fetch, fails closed
// mockFetch.ts - fakes only the global `fetch` type, the one call sellermagnet.ts
// and retry.ts make. Typed as `typeof fetch` itself, so a drift from the real
// fetch signature (wrong arg count, wrong return shape) is a compile error here,
// not just a runtime surprise discovered by a test. Fails closed.
process.env.SELLERMAGNET_API_KEY ??= "test-key";
export interface Call {
endpoint: string;
params: Record<string, string>;
}
export type Route = (endpoint: string, params: URLSearchParams) => [number, unknown, Record<string, string>?];
export const CALLS: Call[] = [];
let currentRoute: Route = blockedRoute;
function blockedRoute(): never {
throw new Error("mockFetch: call install(route) first - no request may reach the real API");
}
export function install(route: Route): void {
currentRoute = route;
}
export function reset(): void {
currentRoute = blockedRoute;
CALLS.length = 0;
}
export function ok(data: unknown): [number, unknown] {
return [200, { success: true, data }];
}
export function error(
status: number,
message = "request failed",
headers: Record<string, string> = {},
): [number, unknown, Record<string, string>] {
return [status, { success: false, error: "error", message }, headers];
}
// The signature below must match `typeof fetch` exactly (minimal subset:
// RequestInfo/URL first arg, options with a signal). If a future real-fetch
// change narrows/widens that shape, `tsc` on this file fails before any test
// runs, catching a mock/reality drift the JS version can only catch at runtime.
const fakeFetch: typeof fetch = async (input, _init) => {
const u = new URL(input instanceof URL ? input : input.toString());
if (!u.searchParams.get("api_key")) throw new Error("api_key must travel as a query parameter");
const endpoint = u.pathname.split("/").pop() ?? "";
CALLS.push({ endpoint, params: Object.fromEntries(u.searchParams) });
const [status, body, headers = {}] = currentRoute(endpoint, u.searchParams);
return {
ok: status >= 200 && status < 300,
status,
headers: { get: (k: string) => headers[k] ?? null } as Headers,
json: async () => {
if (typeof body === "string") throw new Error("not json"); // simulates an HTML error page
return body;
},
} as Response;
};
globalThis.fetch = fakeFetch;
The one mechanical adaptation needed to run sellermagnet.ts/retry.ts unchanged here
retry.ts imports sellermagnet.js with an explicit .js extension, the NodeNext-style ESM convention the TypeScript mock-testing post's Vitest setup uses. This project compiles with CommonJS instead, so Jest needs one moduleNameMapper entry (^(\\.{1,2}/.*)\\.js$ -> $1) to resolve that import to the real sellermagnet.ts file. Nothing in sellermagnet.ts or retry.ts themselves changed, the same byte-for-byte files from the quickstart post run here.
lookup.controller.spec.ts - 12 scenarios against the fails-closed mockFetch layer
// lookup.controller.spec.ts - fails-closed scenario tests for the NestJS
// wrapper. The fake HTTP layer is mockFetch.ts, reused unchanged from the
// TypeScript mock-testing post: it replaces globalThis.fetch itself (typed
// as typeof fetch), which is the layer sellermagnet.ts and retry.ts call.
//
// A library that fakes only nock/undici's HTTP transport (the pattern the
// Express wrapper post used) does not intercept Node's native global fetch
// on every Node build - proved while building this post: with nock's
// disableNetConnect() active, and separately with undici's own MockAgent as
// the global dispatcher, a lookup still reached the real sellermagnet-api.com
// and came back with a real 401. globalThis.fetch replacement has no such
// gap, since it swaps the function the client calls directly rather than a
// transport layer underneath it.
import { Test } from "@nestjs/testing";
import { INestApplication, ValidationPipe } from "@nestjs/common";
import request from "supertest";
import * as mockFetch from "./mockFetch";
import { AppModule } from "./app.module";
const ASIN = "B0CL61F39H";
const MARKETPLACE = "ATVPDKIKX0DER";
function productInfo(price: number | "N/A" = 444.99) {
return {
productInfo: {
asin: ASIN,
title: "PlayStation5 console (slim)",
link: `https://www.amazon.com/dp/${ASIN}`,
buyBoxInfo: { price, currencyCode: "USD", sellerId: "A2L77EE7U53NWQ" },
},
};
}
let app: INestApplication;
// retry.ts's own backoff is small on purpose for a test harness (2**attempt
// seconds, capped at 30, attempts=4 default) - these tests let the real
// timers run, the same way the Express wrapper's Jest suite does, rather
// than faking setTimeout.
jest.setTimeout(20_000);
beforeEach(async () => {
const moduleRef = await Test.createTestingModule({ imports: [AppModule] }).compile();
app = moduleRef.createNestApplication();
app.useGlobalPipes(new ValidationPipe({ transform: true, whitelist: true, forbidNonWhitelisted: true }));
await app.init();
});
afterEach(async () => {
mockFetch.reset(); // reinstalls the closed-by-default blockedRoute
await app.close();
});
test("valid ASIN, cache miss: 200, one upstream call, not cached", async () => {
mockFetch.install(() => mockFetch.ok(productInfo()));
const res = await request(app.getHttpServer()).get(`/lookup/${ASIN}`).query({ marketplaceId: MARKETPLACE });
expect(res.status).toBe(200);
expect(res.body).toEqual({
asin: ASIN,
title: "PlayStation5 console (slim)",
price: 444.99,
currency: "USD",
cached: false,
});
expect(mockFetch.CALLS).toHaveLength(1);
});
test("same lookup again within 300s: served from cache, zero upstream calls", async () => {
mockFetch.install(() => mockFetch.ok(productInfo()));
const first = await request(app.getHttpServer()).get(`/lookup/${ASIN}`).query({ marketplaceId: MARKETPLACE });
const second = await request(app.getHttpServer()).get(`/lookup/${ASIN}`).query({ marketplaceId: MARKETPLACE });
expect(first.body.cached).toBe(false);
expect(second.body.cached).toBe(true);
expect(second.body.price).toBe(444.99);
expect(mockFetch.CALLS).toHaveLength(1); // the second request never reached the upstream route
});
test("malformed ASIN shape: 400, rejected before the network (DTO validation)", async () => {
const res = await request(app.getHttpServer()).get("/lookup/short").query({ marketplaceId: MARKETPLACE });
expect(res.status).toBe(400);
expect(JSON.stringify(res.body)).toContain("asin must be 10 upper-case letters/digits");
expect(mockFetch.CALLS).toHaveLength(0);
});
test("unknown marketplaceId: 400, rejected before the network (DTO validation)", async () => {
const res = await request(app.getHttpServer()).get(`/lookup/${ASIN}`).query({ marketplaceId: "A-UNKNOWN" });
expect(res.status).toBe(400);
expect(JSON.stringify(res.body)).toContain("marketplaceId must be one of");
expect(mockFetch.CALLS).toHaveLength(0);
});
test("lower-case ASIN, cache miss: DTO transform normalizes it before lookup", async () => {
mockFetch.install(() => mockFetch.ok(productInfo()));
const res = await request(app.getHttpServer())
.get(`/lookup/${ASIN.toLowerCase()}`)
.query({ marketplaceId: MARKETPLACE });
expect(res.status).toBe(200);
expect(res.body.asin).toBe(ASIN);
expect(mockFetch.CALLS[0]?.params.asin).toBe(ASIN); // normalized before it reached fetch
});
test('no featured offer price "N/A" decodes to null, not 0', async () => {
mockFetch.install(() => mockFetch.ok(productInfo("N/A")));
const res = await request(app.getHttpServer()).get(`/lookup/${ASIN}`).query({ marketplaceId: MARKETPLACE });
expect(res.body.price).toBeNull();
});
test("upstream 404 (not on this marketplace): 404, not retried, billed", async () => {
mockFetch.install(() => mockFetch.error(404, "Product not found."));
const res = await request(app.getHttpServer()).get(`/lookup/${ASIN}`).query({ marketplaceId: MARKETPLACE });
expect(res.status).toBe(404);
expect(mockFetch.CALLS).toHaveLength(1); // billed once, never retried
});
test("upstream 429 (concurrency cap): retried for free, eventually 200", async () => {
let calls = 0;
mockFetch.install(() => {
calls += 1;
if (calls === 1) return mockFetch.error(429, "Too many concurrent requests.", { "Retry-After": "0" });
return mockFetch.ok(productInfo());
});
const res = await request(app.getHttpServer()).get(`/lookup/${ASIN}`).query({ marketplaceId: MARKETPLACE });
expect(res.status).toBe(200);
expect(mockFetch.CALLS).toHaveLength(2);
});
test("upstream 500 (refunded): retried once, then 200", async () => {
let calls = 0;
mockFetch.install(() => {
calls += 1;
if (calls === 1) return mockFetch.error(500, "Internal error.");
return mockFetch.ok(productInfo());
});
const res = await request(app.getHttpServer()).get(`/lookup/${ASIN}`).query({ marketplaceId: MARKETPLACE });
expect(res.status).toBe(200);
expect(mockFetch.CALLS).toHaveLength(2);
});
test("two upstream 500s in a row: stops after the second, 502", async () => {
mockFetch.install(() => mockFetch.error(500, "Internal error."));
const res = await request(app.getHttpServer()).get(`/lookup/${ASIN}`).query({ marketplaceId: MARKETPLACE });
expect(res.status).toBe(502);
expect(mockFetch.CALLS).toHaveLength(2); // one real attempt, one refunded retry, then it gives up
});
test("upstream 502/503: retried up to 4 attempts, each billed, then 200", async () => {
let calls = 0;
mockFetch.install(() => {
calls += 1;
if (calls < 4) return mockFetch.error(502, "Bad gateway.");
return mockFetch.ok(productInfo());
});
const res = await request(app.getHttpServer()).get(`/lookup/${ASIN}`).query({ marketplaceId: MARKETPLACE });
expect(res.status).toBe(200);
expect(mockFetch.CALLS).toHaveLength(4);
});
test("connection error (never reached the server): 502, not retried, nothing billed", async () => {
mockFetch.install(() => {
throw new TypeError("fetch failed: connection refused");
});
const res = await request(app.getHttpServer()).get(`/lookup/${ASIN}`).query({ marketplaceId: MARKETPLACE });
expect(res.status).toBe(502);
expect(mockFetch.CALLS).toHaveLength(1); // exactly the 1 scripted call fired, no retry
});
Real output: a cache miss then a cache hit, one upstream call total
GET /lookup/B0CL61F39H?marketplaceId=ATVPDKIKX0DER
-> {"asin":"B0CL61F39H","title":"PlayStation5 console (slim)","price":444.99,"currency":"USD","cached":false}
GET /lookup/B0CL61F39H?marketplaceId=ATVPDKIKX0DER (again, within the 300s cache window)
-> {"asin":"B0CL61F39H","title":"PlayStation5 console (slim)","price":444.99,"currency":"USD","cached":true}
upstream calls made: 1
This cache is per worker process
Running the service under PM2 in cluster mode (or several container replicas) means each one holds its own cache, so the same ASIN can be fetched once per worker within the TTL. That is a reasonable default for a single small service; a reader running several workers behind a load balancer should size the TTL around that, or swap in a shared store of their own choice.
Frequently Asked Questions
Why validate with class-validator DTOs instead of a plain function?
Either works. NestJS's ValidationPipe already runs class-validator decorators on every @Param()/@Query() object for free, so a DTO fits the framework's own request pipeline; a hand-written check function (the pattern the Express wrapper post uses) needs its own call site in every route instead.
Does the cache in this wrapper work across multiple Node processes?
No. CacheService wraps a plain in-process Map; each Nest worker process keeps its own copy. Several PM2 cluster workers sharing one cache need an external store, which is outside this post's scope.
Which status codes does the wrapper retry?
429 is waited out for free, a 500 is retried once since it is refunded, and 502/503 are retried up to 4 attempts total since each is billed. A 404 is never retried.
Why does a plain fetch failure need its own branch instead of ApiError handling?
A refused connection, a DNS failure, or our own AbortSignal firing throws a TypeError straight from fetch, not the client's ApiError. getWithRetry only retries ApiError instances, so without a separate branch for it, a dropped connection reaches the client as an unhandled 500 instead of the wrapper's own 502.
Can I validate the DTO fields with zod or Joi instead of class-validator?
Yes, Nest supports a custom ValidationPipe backed by any schema library. class-validator is used here because it is the decorator-based validator NestJS documents by default and needs no extra pipe wiring beyond ValidationPipe itself.
Why does this wrapper use globalThis.fetch replacement instead of nock for its tests?
Faking only the HTTP transport underneath fetch did not reliably intercept Node's native fetch while building this post; a test still reached the real API. Replacing globalThis.fetch directly, the same pattern the TypeScript mock-testing post uses, has no such gap.
Bottom line: validate with class-validator DTOs before any network call, cache repeat lookups for free in a short-lived per-process CacheService, and reuse the TypeScript quickstart's own client and retry policy unchanged. Every behaviour here came from running npx jest against real code with only globalThis.fetch faked - see the TypeScript mock-testing guide for the client's own retry details and the API documentation for every endpoint.