{"id":26630293,"url":"https://github.com/elite174/api-maker","last_synced_at":"2025-03-24T13:18:00.703Z","repository":{"id":221640196,"uuid":"754961166","full_name":"elite174/api-maker","owner":"elite174","description":"Highly customizable small lib with 0 dependencies allows you to build API functions with mocks.","archived":false,"fork":false,"pushed_at":"2024-02-20T04:26:38.000Z","size":48,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-03-16T07:48:19.898Z","etag":null,"topics":["api","api-client","api-maker","fetch","mock","xhr"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/elite174.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null}},"created_at":"2024-02-09T05:45:36.000Z","updated_at":"2024-02-09T12:20:58.000Z","dependencies_parsed_at":"2024-02-09T06:45:21.719Z","dependency_job_id":null,"html_url":"https://github.com/elite174/api-maker","commit_stats":null,"previous_names":["elite174/api-maker"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/elite174%2Fapi-maker","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/elite174%2Fapi-maker/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/elite174%2Fapi-maker/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/elite174%2Fapi-maker/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/elite174","download_url":"https://codeload.github.com/elite174/api-maker/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245276101,"owners_count":20588894,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api","api-client","api-maker","fetch","mock","xhr"],"created_at":"2025-03-24T13:17:59.972Z","updated_at":"2025-03-24T13:18:00.696Z","avatar_url":"https://github.com/elite174.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# @elite174/api-maker\n\n[![version](https://img.shields.io/npm/v/@elite174/api-maker?style=for-the-badge)](https://www.npmjs.com/package/@elite174/api-maker)\n![npm](https://img.shields.io/npm/dw/@elite174/api-maker?style=for-the-badge)\n\nHighly customizable small lib with 0 dependencies allows you to build API functions with mocks.\n\nFeatures:\n\n- Provide mock handlers if your backend is not ready yet\n- Override mock handlers, request parameters and response handlers in 3 layers (api service creation, api function creation, api call)\n- Typed parameters\n- XHR support\n\n## Installation\n\n```\npnpm i @elite174/api-maker\n```\n\nIn browser\n\n```html\n\u003cscript type=\"module\"\u003e\n  // specify correct version here\n  import { APIMaker } from \"https://cdn.jsdelivr.net/npm/@elite174/api-maker@latest/dist/index.js\";\n\n  const api = new APIMaker({\n    base: \"https://jsonplaceholder.typicode.com\",\n  });\n\n  const getData = api.create(() =\u003e ({\n    path: \"/todos\",\n  }));\n\n  getData().then(console.log);\n\u003c/script\u003e\n```\n\n## Examples\n\n```ts\nimport { APIMaker } from \"@elite174/api-maker\";\n\n// Create API controller instance\nconst api = new APIMaker({\n  base: \"https://jsonplaceholder.typicode.com\",\n  // You may specify custom response handler\n  // by default for fetch requests it's response.json().\n  // Later you may override it during api creation or api call.\n  defaultResponseHandler: (response) =\u003e response.json(),\n  // You may also pass extra options to fetch\n  // sharedRequestOptions: { credentials: \"include\" },\n});\n\n// Create api route\n// Specify result type (unknown) and params type (number)\nconst getUser = api.create\u003cunknown, number\u003e((id) =\u003e ({\n  path: `/users/${id}`,\n}));\n\n// Call api route!\ngetUser(1).then(console.log);\n\n//-----------------\n\n// If your BE is not ready yet you can make a fetcher with mocked data\nconst getUserMocked = api.create\u003c{ name: string }, number\u003e((id) =\u003e ({\n  path: `/users/${id}`,\n  // Tree shaking will remove this code in production\n  mockHandler: import.meta.env.PROD ? undefined : async (id) =\u003e ({ name: `User: ${id}: John Doe` }),\n}));\n\n// Call api route!\ngetUserMocked(1, {\n  useMockedData: true,\n  // You may override the mock handler provided in api creation\n  // mockHandler: async () =\u003e ({ name: \"This handler will be used\" }),\n}).then(console.log);\n\n//-----------------\n\n// You can override default response handler\nconst getUserCustomResponseHandler = api.create\u003cunknown, number\u003e((id) =\u003e ({\n  path: `/users/${id}`,\n  responseHandler: async (response) =\u003e response.text(),\n}));\n\n// Call api route!\ngetUserCustomResponseHandler(1, {\n  // You may also override responseHandler during api call\n  // responseHandler: (response) =\u003e response.blob(),\n}).then(console.log);\n\n//-----------------\n\n// You may add some listeners to handle specific status codes\napi.on(404, () =\u003e console.log(\"404 error!\"));\n\n//-----------------\n// There's support for XHR requests!\nconst getUserXHR = api.createXHR\u003cany, number\u003e((id) =\u003e ({\n  path: `/users/${id}`,\n}));\n\ngetUserXHR(1).sendRequest().then(console.log);\n```\n\nSee more examples in the [test file](https://github.com/elite174/api-maker/blob/master/src/lib/index.test.ts).\n\n## Types\n\n```ts\nexport declare type APIControllerConfig = {\n  /** Base URL */\n  base?: string;\n  /**\n   * Shared request options which are used for all the requests\n   * @default { method: 'GET' }\n   */\n  sharedRequestOptions?: RequestInit;\n  /**\n   * Response handler which is used for all fetch requests\n   * @default response =\u003e response.json()\n   */\n  defaultResponseHandler?: ResponseHandler;\n};\n\n/**\n * We have 3 layers:\n * 1. API service creation\n * 2. API route creation\n * 3. API call\n *\n * Things you can override at each layer:\n * 1. RequestInit params\n * 2. Mock handler (only on 2 and 3 layer)\n * 3. Response handler\n */\n/**\n * The APIMaker class is responsible for creating and managing API requests.\n */\nexport declare class APIMaker {\n  private logger?;\n  private statusHandlers;\n  private config;\n  private getFullPath;\n  constructor(config?: APIControllerConfig, logger?: Logger | undefined);\n  /** When enabled mock handlers are used where possible */\n  mockModeEnabled: boolean;\n  /**\n   * Sets the shared request options for all the requests.\n   * If an object is passed, it will override the options defined in the constructor.\n   * You may pass a function that receives the current shared request options and returns the new options.\n   */\n  setSharedRequestOptions(\n    requestOptions: RequestInit | ((currentSharedRequestOptions: RequestInit) =\u003e RequestInit)\n  ): void;\n  on(statusCode: number, statusHandler: StatusHandler): void;\n  off(statusCode: number, statusHandler: StatusHandler): void;\n  createXHR\u003cTResult, TParams = void\u003e(requestCreator: XHRRequestCreator\u003cTParams, TResult\u003e): XHRFetcher\u003cTParams, TResult\u003e;\n  create\u003cTResult, TParams = void\u003e(requestCreator: FetchRequestCreator\u003cTParams, TResult\u003e): Fetcher\u003cTParams, TResult\u003e;\n}\n\nexport declare function deepMerge\u003cT = any\u003e(...objects: (Record\u003cstring, any\u003e | undefined)[]): T;\n\nexport declare const DEFAULT_API_MAKER_CONFIG: {\n  base: string;\n  sharedRequestOptions: {\n    method: string;\n  };\n  defaultResponseHandler: (response: Response) =\u003e Promise\u003cany\u003e;\n};\n\n/**\n * Represents a function that fetches data from an API.\n * @template TParams The type of the API parameters.\n * @template TResult The type of the API response.\n * @param apiParams The parameters to be passed to the API.\n * @param options Additional options for the fetcher.\n * @param options.customRequestOptions Custom request options to be passed to the fetch function.\n * @param options.useMockedData Specifies whether to use mocked data instead of making a real API request.\n * @param options.mockHandler A function that handles the mocked API request and returns the mocked response.\n * @param options.responseHandler A function that handles the API response and returns the processed result.\n * @returns A promise that resolves to the API response.\n */\nexport declare type Fetcher\u003cTParams, TResult\u003e = (\n  apiParams: TParams,\n  options?: {\n    customRequestOptions?: RequestInit;\n    useMockedData?: boolean;\n    mockHandler?: MockHandler\u003cTParams, TResult\u003e;\n    responseHandler?: ResponseHandler\u003cTResult\u003e;\n  }\n) =\u003e Promise\u003cTResult\u003e;\n\n/**\n * Represents a function that creates a fetch request.\n * @template TParams The type of the request parameters.\n * @template TResult The type of the request result.\n * @param params The request parameters.\n * @returns An object containing the request path, optional request options, mock handler, and response handler.\n */\nexport declare type FetchRequestCreator\u003cTParams, TResult\u003e = (params: TParams) =\u003e {\n  path: string;\n  requestOptions?: RequestInit;\n  mockHandler?: MockHandler\u003cTParams, TResult\u003e;\n  responseHandler?: ResponseHandler\u003cTResult\u003e;\n};\n\ndeclare interface Logger {\n  info(message: string): void;\n}\n\nexport declare const makeLogMessage: (message: string) =\u003e string;\n\nexport declare type MockHandler\u003cTParams, TResult\u003e = (requestParams: TParams) =\u003e Promise\u003cTResult\u003e;\n\nexport declare type ResponseHandler\u003cTResult = any\u003e = (response: Response) =\u003e Promise\u003cTResult\u003e;\n\nexport declare type StatusHandler = (response: Response) =\u003e void;\n\n/**\n * Represents a function that fetches data using XMLHttpRequest.\n * @template TParams - The type of the API parameters.\n * @template TResult - The type of the API result.\n * @param apiParams - The API parameters.\n * @param options - The options for the fetcher.\n * @param options.customRequestOptions - Custom request options for the XMLHttpRequest.\n * @param options.useMockedData - Indicates whether to use mocked data.\n * @param options.mockHandler - The mock handler for generating mocked data.\n * @returns An object containing the XMLHttpRequest and a function to send the request and get the result.\n */\nexport declare type XHRFetcher\u003cTParams, TResult\u003e = (\n  apiParams: TParams,\n  options?: {\n    customRequestOptions?: RequestInit;\n    useMockedData?: boolean;\n    mockHandler?: MockHandler\u003cTParams, TResult\u003e;\n  }\n) =\u003e {\n  xhr: XMLHttpRequest;\n  sendRequest: () =\u003e Promise\u003cTResult\u003e;\n};\n\n/**\n * Represents a function that creates an XHR request.\n * @template TParams The type of the request parameters.\n * @template TResult The type of the request result.\n * @param params The request parameters.\n * @returns An object containing the request path, optional request options, and a mock handler.\n */\nexport declare type XHRRequestCreator\u003cTParams, TResult\u003e = (params: TParams) =\u003e {\n  path: string;\n  requestOptions?: RequestInit;\n  mockHandler?: MockHandler\u003cTParams, TResult\u003e;\n};\n```\n\n## Lisence\n\nMIT\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Felite174%2Fapi-maker","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Felite174%2Fapi-maker","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Felite174%2Fapi-maker/lists"}