@tahanabavi/typefetch 1.0.2 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,36 +0,0 @@
1
- name: Publish Package
2
-
3
- on:
4
- push:
5
- branches:
6
- - main
7
- paths:
8
- - 'package.json'
9
- - 'src/**'
10
- - 'README.md'
11
- - '.github/workflows/publish.yml'
12
-
13
- jobs:
14
- build-and-publish:
15
- runs-on: ubuntu-latest
16
-
17
- steps:
18
- - name: Checkout repository
19
- uses: actions/checkout@v3
20
-
21
- - name: Setup Node.js
22
- uses: actions/setup-node@v3
23
- with:
24
- node-version: 20
25
- registry-url: https://registry.npmjs.org/
26
-
27
- - name: Install dependencies
28
- run: npm install
29
-
30
- - name: Build package
31
- run: npm run build
32
-
33
- - name: Publish to npm
34
- run: npm publish --access public
35
- env:
36
- NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
@@ -1 +0,0 @@
1
- export {};
@@ -1,108 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const zod_1 = require("zod");
4
- const client_1 = require("../client");
5
- // Mock fetch globally
6
- global.fetch = jest.fn();
7
- const contracts = {
8
- user: {
9
- getUser: {
10
- method: "GET",
11
- path: "/user",
12
- request: zod_1.z.object({ id: zod_1.z.string() }),
13
- response: zod_1.z.object({ id: zod_1.z.string(), name: zod_1.z.string() }),
14
- },
15
- createUser: {
16
- method: "POST",
17
- path: "/user",
18
- auth: true,
19
- request: zod_1.z.object({ name: zod_1.z.string() }),
20
- response: zod_1.z.object({ id: zod_1.z.string(), name: zod_1.z.string() }),
21
- },
22
- },
23
- };
24
- describe("ApiClient", () => {
25
- let client;
26
- beforeEach(() => {
27
- jest.clearAllMocks();
28
- client = new client_1.ApiClient({ baseUrl: "https://api.test.com" }, contracts);
29
- client.init();
30
- });
31
- it("should initialize modules correctly", () => {
32
- expect(client.modules.user).toBeDefined();
33
- expect(typeof client.modules.user.getUser).toBe("function");
34
- });
35
- it("should call fetch with correct URL and headers", async () => {
36
- fetch.mockResolvedValueOnce({
37
- ok: true,
38
- json: async () => ({ id: "1", name: "John" }),
39
- });
40
- const res = await client.modules.user.getUser({ id: "1" });
41
- expect(fetch).toHaveBeenCalledWith("https://api.test.com/user", {
42
- method: "GET",
43
- headers: { "Content-Type": "application/json" },
44
- body: undefined,
45
- });
46
- expect(res).toEqual({ id: "1", name: "John" });
47
- });
48
- it("should throw validation error if input is invalid", async () => {
49
- await expect(client.modules.user.getUser({}))
50
- .rejects.toBeInstanceOf(zod_1.ZodError);
51
- });
52
- it("should handle auth header when token is provided", async () => {
53
- const authedClient = new client_1.ApiClient({ baseUrl: "https://api.test.com", token: "mytoken" }, contracts);
54
- authedClient.init();
55
- fetch.mockResolvedValueOnce({
56
- ok: true,
57
- json: async () => ({ id: "2", name: "Alice" }),
58
- });
59
- await authedClient.modules.user.createUser({ name: "Alice" });
60
- expect(fetch).toHaveBeenCalledWith("https://api.test.com/user", {
61
- method: "POST",
62
- headers: {
63
- "Content-Type": "application/json",
64
- Authorization: "Bearer mytoken",
65
- },
66
- body: JSON.stringify({ name: "Alice" }),
67
- });
68
- });
69
- it("should throw error if auth required and no token provided", async () => {
70
- await expect(client.modules.user.createUser({ name: "Alice" })).rejects.toThrow(client_1.RichError);
71
- });
72
- it("should call errorHandler when error occurs", async () => {
73
- const handler = jest.fn();
74
- client.onError(handler);
75
- fetch.mockResolvedValueOnce({
76
- ok: false,
77
- status: 400,
78
- statusText: "Bad Request",
79
- json: async () => ({ message: "Invalid input" }),
80
- });
81
- await expect(client.modules.user.getUser({ id: "bad" })).rejects.toThrow();
82
- expect(handler).toHaveBeenCalled();
83
- });
84
- it("should apply responseTransform", async () => {
85
- client.useResponseTransform((data) => ({ ...data, transformed: true }));
86
- fetch.mockResolvedValueOnce({
87
- ok: true,
88
- json: async () => ({ id: "1", name: "John" }),
89
- });
90
- const res = await client.modules.user.getUser({ id: "1" });
91
- expect(res).toEqual({ id: "1", name: "John", transformed: true });
92
- });
93
- it("should execute middleware in order", async () => {
94
- const logs = [];
95
- client.use(async (ctx, next) => {
96
- logs.push("before");
97
- const res = await next();
98
- logs.push("after");
99
- return res;
100
- });
101
- fetch.mockResolvedValueOnce({
102
- ok: true,
103
- json: async () => ({ id: "1", name: "John" }),
104
- });
105
- await client.modules.user.getUser({ id: "1" });
106
- expect(logs).toEqual(["before", "after"]);
107
- });
108
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,85 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const auth_1 = require("../middlewares/auth");
4
- const cache_1 = require("../middlewares/cache");
5
- const logging_1 = require("../middlewares/logging");
6
- const retry_1 = require("../middlewares/retry");
7
- describe("middlewares", () => {
8
- const mockCtx = (url = "/test", method = "GET") => ({
9
- url,
10
- init: { method, headers: {} },
11
- });
12
- const mockNext = (response = { ok: true, status: 200 }) => jest.fn().mockResolvedValue(new Response(JSON.stringify(response)));
13
- // ---------------- AUTH ----------------
14
- it("authMiddleware should add refreshed token", async () => {
15
- const ctx = mockCtx();
16
- const next = mockNext();
17
- await (0, auth_1.authMiddleware)(ctx, next, {
18
- refreshToken: async () => "NEW_TOKEN",
19
- });
20
- expect(ctx.init.headers["Authorization"]).toBe("Bearer NEW_TOKEN");
21
- expect(next).toHaveBeenCalled();
22
- });
23
- it("authMiddleware should skip if no refreshToken provided", async () => {
24
- const ctx = mockCtx();
25
- const next = mockNext();
26
- await (0, auth_1.authMiddleware)(ctx, next, {});
27
- expect(ctx.init.headers["Authorization"]).toBeUndefined();
28
- expect(next).toHaveBeenCalled();
29
- });
30
- // ---------------- CACHE ----------------
31
- it("cacheMiddleware should cache GET responses", async () => {
32
- const ctx = mockCtx("/users", "GET");
33
- const next = mockNext({ users: [1, 2, 3] });
34
- const middleware = (0, cache_1.cacheMiddleware)({ ttl: 1000 });
35
- const res1 = await middleware(ctx, next);
36
- const res2 = await middleware(ctx, next);
37
- expect(next).toHaveBeenCalledTimes(1); // only first time
38
- const data2 = await res2.json();
39
- expect(data2.users).toEqual([1, 2, 3]);
40
- });
41
- it("cacheMiddleware should bypass cache for non-GET requests", async () => {
42
- const ctx = mockCtx("/users", "POST");
43
- const next = mockNext({ ok: true });
44
- const middleware = (0, cache_1.cacheMiddleware)();
45
- await middleware(ctx, next);
46
- expect(next).toHaveBeenCalledTimes(1);
47
- });
48
- // ---------------- LOGGING ----------------
49
- it("loggingMiddleware should log request and response", async () => {
50
- const ctx = mockCtx();
51
- const next = mockNext();
52
- const logSpy = jest.spyOn(console, "log").mockImplementation(() => { });
53
- await (0, logging_1.loggingMiddleware)(ctx, next, {
54
- logRequest: true,
55
- logResponse: true,
56
- debug: true,
57
- });
58
- expect(logSpy).toHaveBeenCalledWith("➡️ Request:", ctx.url, ctx.init);
59
- expect(logSpy).toHaveBeenCalledWith("⬅️ Response:", 200);
60
- logSpy.mockRestore();
61
- });
62
- // ---------------- RETRY ----------------
63
- it("retryMiddleware should retry failed requests", async () => {
64
- const ctx = mockCtx();
65
- let attempt = 0;
66
- const next = jest.fn().mockImplementation(() => {
67
- attempt++;
68
- if (attempt < 2)
69
- throw new Error("fail");
70
- return Promise.resolve(new Response(JSON.stringify({ ok: true })));
71
- });
72
- const middleware = (0, retry_1.retryMiddleware)({ maxRetries: 3, delay: 10 });
73
- const res = await middleware(ctx, next);
74
- const json = await res.json();
75
- expect(json.ok).toBe(true);
76
- expect(next).toHaveBeenCalledTimes(2);
77
- });
78
- it("retryMiddleware should throw after exceeding maxRetries", async () => {
79
- const ctx = mockCtx();
80
- const next = jest.fn().mockRejectedValue(new Error("fail always"));
81
- const middleware = (0, retry_1.retryMiddleware)({ maxRetries: 2, delay: 10 });
82
- await expect(middleware(ctx, next)).rejects.toThrow("fail always");
83
- expect(next).toHaveBeenCalledTimes(3); // initial + 2 retries
84
- });
85
- });
package/dist/client.d.ts DELETED
@@ -1,31 +0,0 @@
1
- import { Contracts, Middleware, ErrorLike, EndpointMethods } from "./types";
2
- export declare class RichError extends Error implements ErrorLike {
3
- status?: number;
4
- code?: string;
5
- title?: string;
6
- detail?: string;
7
- errors?: Record<string, string[]>;
8
- constructor(error: Partial<ErrorLike> & {
9
- message: string;
10
- });
11
- }
12
- export declare class ApiClient<C extends Contracts, E extends ErrorLike = RichError> {
13
- private config;
14
- private contracts;
15
- private middlewares;
16
- private errorHandler?;
17
- private responseTransform;
18
- private _modules;
19
- constructor(config: {
20
- baseUrl: string;
21
- token?: string;
22
- }, contracts: C);
23
- init(): void;
24
- get modules(): { [M in keyof C]: EndpointMethods<C[M]>; };
25
- use<T>(middleware: Middleware<T>, options?: T): void;
26
- onError(handler: (error: E) => void): void;
27
- useResponseTransform(fn: (data: any) => any): void;
28
- private request;
29
- private createError;
30
- private normalizeError;
31
- }
package/dist/client.js DELETED
@@ -1,98 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ApiClient = exports.RichError = void 0;
4
- class RichError extends Error {
5
- constructor(error) {
6
- super(error.message);
7
- Object.assign(this, error);
8
- }
9
- }
10
- exports.RichError = RichError;
11
- class ApiClient {
12
- constructor(config, contracts) {
13
- this.config = config;
14
- this.contracts = contracts;
15
- this.middlewares = [];
16
- this.responseTransform = (d) => d;
17
- }
18
- init() {
19
- const modules = {};
20
- for (const moduleName in this.contracts) {
21
- const module = this.contracts[moduleName];
22
- modules[moduleName] = {};
23
- for (const endpointName in module) {
24
- const endpoint = module[endpointName];
25
- modules[moduleName][endpointName] = (input) => this.request(endpoint, input);
26
- }
27
- }
28
- this._modules = modules;
29
- }
30
- get modules() {
31
- return this._modules;
32
- }
33
- use(middleware, options) {
34
- this.middlewares.push({ fn: middleware, options });
35
- }
36
- onError(handler) {
37
- this.errorHandler = handler;
38
- }
39
- useResponseTransform(fn) {
40
- this.responseTransform = fn;
41
- }
42
- async request(endpoint, input) {
43
- endpoint.request.parse(input);
44
- if (endpoint.auth && !this.config.token) {
45
- const error = this.createError({
46
- message: `Missing token for ${endpoint.path}`,
47
- status: 401,
48
- code: "NO_TOKEN",
49
- });
50
- this.errorHandler?.(error);
51
- throw error;
52
- }
53
- const headers = { "Content-Type": "application/json" };
54
- if (endpoint.auth && this.config.token)
55
- headers["Authorization"] = `Bearer ${this.config.token}`;
56
- const ctx = {
57
- url: this.config.baseUrl + endpoint.path,
58
- init: {
59
- method: endpoint.method,
60
- headers,
61
- body: endpoint.method !== "GET" ? JSON.stringify(input) : undefined,
62
- },
63
- };
64
- const runner = this.middlewares.reduceRight((next, mw) => () => mw.fn(ctx, next, mw.options), () => fetch(ctx.url, ctx.init));
65
- try {
66
- const res = await runner();
67
- if (!res.ok) {
68
- const errorData = await res.json().catch(() => ({}));
69
- const error = this.createError({
70
- message: errorData.message || res.statusText,
71
- status: res.status,
72
- code: errorData.code,
73
- title: errorData.title,
74
- detail: errorData.detail,
75
- errors: errorData.errors,
76
- });
77
- this.errorHandler?.(error);
78
- throw error;
79
- }
80
- const json = await res.json();
81
- return this.responseTransform(endpoint.response.parse(json));
82
- }
83
- catch (err) {
84
- const error = this.normalizeError(err);
85
- this.errorHandler?.(error);
86
- throw error;
87
- }
88
- }
89
- createError(error) {
90
- return new RichError(error);
91
- }
92
- normalizeError(err) {
93
- if (err instanceof RichError)
94
- return err;
95
- return this.createError({ message: err.message || "Unknown error" });
96
- }
97
- }
98
- exports.ApiClient = ApiClient;
@@ -1,5 +0,0 @@
1
- import { Middleware } from "../types";
2
- export type AuthOptions = {
3
- refreshToken?: () => Promise<string>;
4
- };
5
- export declare const authMiddleware: Middleware<AuthOptions>;
@@ -1,17 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.authMiddleware = void 0;
4
- const authMiddleware = async (ctx, next, options) => {
5
- if (options?.refreshToken) {
6
- try {
7
- const newToken = await options.refreshToken();
8
- ctx.init.headers = {
9
- ...ctx.init.headers,
10
- Authorization: `Bearer ${newToken}`
11
- };
12
- }
13
- catch { }
14
- }
15
- return next();
16
- };
17
- exports.authMiddleware = authMiddleware;
@@ -1,5 +0,0 @@
1
- import { MiddlewareContext, MiddlewareNext } from "../types";
2
- export type CacheOptions = {
3
- ttl?: number;
4
- };
5
- export declare const cacheMiddleware: (options?: CacheOptions) => (ctx: MiddlewareContext, next: MiddlewareNext) => Promise<Response>;
@@ -1,25 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.cacheMiddleware = void 0;
4
- const cacheMiddleware = (options = {}) => {
5
- const { ttl = 60000 } = options;
6
- const cache = new Map();
7
- return async (ctx, next) => {
8
- if (ctx.init.method === "GET") {
9
- const cached = cache.get(ctx.url);
10
- const now = Date.now();
11
- if (cached && cached.expires > now)
12
- return new Response(JSON.stringify(cached.data));
13
- const res = await next();
14
- const data = await res
15
- .clone()
16
- .json()
17
- .catch(() => null);
18
- if (data)
19
- cache.set(ctx.url, { data, expires: now + ttl });
20
- return res;
21
- }
22
- return next();
23
- };
24
- };
25
- exports.cacheMiddleware = cacheMiddleware;
@@ -1,7 +0,0 @@
1
- import { Middleware } from "../types";
2
- export type LoggingOptions = {
3
- logRequest?: boolean;
4
- logResponse?: boolean;
5
- debug?: boolean;
6
- };
7
- export declare const loggingMiddleware: Middleware<LoggingOptions>;
@@ -1,13 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.loggingMiddleware = void 0;
4
- const loggingMiddleware = async (ctx, next, options) => {
5
- const { logRequest = true, logResponse = true, debug = true } = options || {};
6
- if (debug && logRequest)
7
- console.log("➡️ Request:", ctx.url, ctx.init);
8
- const res = await next();
9
- if (debug && logResponse)
10
- console.log("⬅️ Response:", res.status);
11
- return res;
12
- };
13
- exports.loggingMiddleware = loggingMiddleware;
@@ -1,6 +0,0 @@
1
- import { Middleware } from "../types";
2
- export type RetryOptions = {
3
- maxRetries?: number;
4
- delay?: number;
5
- };
6
- export declare const retryMiddleware: (options?: RetryOptions) => Middleware;
@@ -1,22 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.retryMiddleware = void 0;
4
- const retryMiddleware = (options) => {
5
- const { maxRetries = 3, delay = 500 } = options || {};
6
- const middleware = async (ctx, next) => {
7
- let attempt = 0;
8
- while (true) {
9
- try {
10
- return await next();
11
- }
12
- catch (err) {
13
- if (attempt >= maxRetries)
14
- throw err;
15
- attempt++;
16
- await new Promise(r => setTimeout(r, delay * 2 ** attempt));
17
- }
18
- }
19
- };
20
- return middleware;
21
- };
22
- exports.retryMiddleware = retryMiddleware;
package/jest.config.ts DELETED
@@ -1,18 +0,0 @@
1
- import type { Config } from "jest";
2
-
3
- const config: Config = {
4
- preset: "ts-jest",
5
- testEnvironment: "node",
6
- roots: ["<rootDir>/src"],
7
- moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"],
8
- transform: {
9
- "^.+\\.(ts|tsx)$": "ts-jest",
10
- },
11
- testMatch: ["**/*.test.ts", "**/*.test.tsx"],
12
- collectCoverage: true,
13
- collectCoverageFrom: ["src/**/*.{ts,tsx}", "!src/**/*.d.ts"],
14
- coverageDirectory: "coverage",
15
- clearMocks: true,
16
- };
17
-
18
- export default config;
@@ -1,137 +0,0 @@
1
- import { z, ZodError } from "zod";
2
- import { ApiClient, RichError } from "../client";
3
- import { Contracts } from "../types";
4
-
5
- // Mock fetch globally
6
- global.fetch = jest.fn();
7
-
8
- const contracts: Contracts = {
9
- user: {
10
- getUser: {
11
- method: "GET",
12
- path: "/user",
13
- request: z.object({ id: z.string() }),
14
- response: z.object({ id: z.string(), name: z.string() }),
15
- },
16
- createUser: {
17
- method: "POST",
18
- path: "/user",
19
- auth: true,
20
- request: z.object({ name: z.string() }),
21
- response: z.object({ id: z.string(), name: z.string() }),
22
- },
23
- },
24
- };
25
-
26
- describe("ApiClient", () => {
27
- let client: ApiClient<typeof contracts>;
28
-
29
- beforeEach(() => {
30
- jest.clearAllMocks();
31
- client = new ApiClient({ baseUrl: "https://api.test.com" }, contracts);
32
- client.init();
33
- });
34
-
35
- it("should initialize modules correctly", () => {
36
- expect(client.modules.user).toBeDefined();
37
- expect(typeof client.modules.user.getUser).toBe("function");
38
- });
39
-
40
- it("should call fetch with correct URL and headers", async () => {
41
- (fetch as jest.Mock).mockResolvedValueOnce({
42
- ok: true,
43
- json: async () => ({ id: "1", name: "John" }),
44
- });
45
-
46
- const res = await client.modules.user.getUser({ id: "1" });
47
- expect(fetch).toHaveBeenCalledWith("https://api.test.com/user", {
48
- method: "GET",
49
- headers: { "Content-Type": "application/json" },
50
- body: undefined,
51
- });
52
- expect(res).toEqual({ id: "1", name: "John" });
53
- });
54
-
55
- it("should throw validation error if input is invalid", async () => {
56
- await expect(client.modules.user.getUser({} as any))
57
- .rejects.toBeInstanceOf(ZodError);
58
- });
59
-
60
- it("should handle auth header when token is provided", async () => {
61
- const authedClient = new ApiClient(
62
- { baseUrl: "https://api.test.com", token: "mytoken" },
63
- contracts
64
- );
65
- authedClient.init();
66
-
67
- (fetch as jest.Mock).mockResolvedValueOnce({
68
- ok: true,
69
- json: async () => ({ id: "2", name: "Alice" }),
70
- });
71
-
72
- await authedClient.modules.user.createUser({ name: "Alice" });
73
-
74
- expect(fetch).toHaveBeenCalledWith("https://api.test.com/user", {
75
- method: "POST",
76
- headers: {
77
- "Content-Type": "application/json",
78
- Authorization: "Bearer mytoken",
79
- },
80
- body: JSON.stringify({ name: "Alice" }),
81
- });
82
- });
83
-
84
- it("should throw error if auth required and no token provided", async () => {
85
- await expect(
86
- client.modules.user.createUser({ name: "Alice" })
87
- ).rejects.toThrow(RichError);
88
- });
89
-
90
- it("should call errorHandler when error occurs", async () => {
91
- const handler = jest.fn();
92
- client.onError(handler);
93
-
94
- (fetch as jest.Mock).mockResolvedValueOnce({
95
- ok: false,
96
- status: 400,
97
- statusText: "Bad Request",
98
- json: async () => ({ message: "Invalid input" }),
99
- });
100
-
101
- await expect(client.modules.user.getUser({ id: "bad" })).rejects.toThrow();
102
-
103
- expect(handler).toHaveBeenCalled();
104
- });
105
-
106
- it("should apply responseTransform", async () => {
107
- client.useResponseTransform((data) => ({ ...data, transformed: true }));
108
-
109
- (fetch as jest.Mock).mockResolvedValueOnce({
110
- ok: true,
111
- json: async () => ({ id: "1", name: "John" }),
112
- });
113
-
114
- const res = await client.modules.user.getUser({ id: "1" });
115
- expect(res).toEqual({ id: "1", name: "John", transformed: true });
116
- });
117
-
118
- it("should execute middleware in order", async () => {
119
- const logs: string[] = [];
120
-
121
- client.use(async (ctx, next) => {
122
- logs.push("before");
123
- const res = await next();
124
- logs.push("after");
125
- return res;
126
- });
127
-
128
- (fetch as jest.Mock).mockResolvedValueOnce({
129
- ok: true,
130
- json: async () => ({ id: "1", name: "John" }),
131
- });
132
-
133
- await client.modules.user.getUser({ id: "1" });
134
-
135
- expect(logs).toEqual(["before", "after"]);
136
- });
137
- });