{"id":13678244,"url":"https://github.com/FxOmar/Nixify","last_synced_at":"2025-04-29T12:34:18.799Z","repository":{"id":60069307,"uuid":"349475863","full_name":"FxOmar/Nixify","owner":"FxOmar","description":"🌴 A tiny human-friendly JavaScript HTTP client library based on the browser with no dependencies.","archived":false,"fork":false,"pushed_at":"2024-01-12T19:13:33.000Z","size":519,"stargazers_count":10,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"master","last_synced_at":"2024-11-02T03:33:24.432Z","etag":null,"topics":["fetch-api","http","http-client","typescript"],"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/FxOmar.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","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}},"created_at":"2021-03-19T15:48:34.000Z","updated_at":"2024-02-08T17:38:32.000Z","dependencies_parsed_at":"2024-01-09T23:31:00.652Z","dependency_job_id":"7a859b62-6ecf-4f92-b33f-6a917d8b2f30","html_url":"https://github.com/FxOmar/Nixify","commit_stats":null,"previous_names":["fxomar/nixify","fxomar/reqeza"],"tags_count":16,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/FxOmar%2FNixify","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/FxOmar%2FNixify/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/FxOmar%2FNixify/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/FxOmar%2FNixify/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/FxOmar","download_url":"https://codeload.github.com/FxOmar/Nixify/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":224173677,"owners_count":17268153,"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":["fetch-api","http","http-client","typescript"],"created_at":"2024-08-02T13:00:51.468Z","updated_at":"2024-11-11T20:31:14.139Z","avatar_url":"https://github.com/FxOmar.png","language":"TypeScript","readme":"# Nixify HTTP Client Library\n\n\u003e Nixify is a lightweight and minimalistic JavaScript HTTP client based on the browser's [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) with no dependencies. It's designed for simplicity and ease of use in browser environments, providing a concise API for making HTTP requests to various services.\n\n## Installation\n\n#### Package manager\n\nUsing npm:\n```bash\nnpm install nixify\n```\nUsing pnpm:\n```bash\npnpm add nixify\n```\nUsing yarn:\n```bash\nyarn add nixify\n```\n\nTo import Nixify you have to use ECMAScript\n\n```javascript\nimport Nixify from \"nixify\";\n```\nUsing jsdelivr:\n```html\n\u003cscript type=\"module\"\u003e\n  import nixify from 'https://cdn.jsdelivr.net/npm/nixify@3.1.1/+esm'\n\u003c/script\u003e\n```\n\n## Nixify Features\n\n- **Lightweight**: Minimalistic HTTP client designed for simplicity.\n- **First-class TypeScript Support**: Developed entirely in TypeScript for a robust experience.\n- **Fetch API Integration**: Built on the browser's Fetch API for HTTP requests.\n- **Shortcut Methods**: Shorthand methods like `Nixify.get().text()` for readability.\n- **Retry Request**: automatic retry of failed requests based on status codes.\n- **Configurable Services**: Easily configure instances for different services.\n- **Header Management**: Set headers globally or for specific instances.\n- **Dynamic Route Matching with Params**: Support for dynamic route matching with parameters.\n- **Hooks**: Execute functions before/after requests, with a `beforeRetry` hook.\n- **Automatic JSON Handling**: Streamlined interaction with JSON responses.\n- **Cancel Requests**: Efficiently manage ongoing requests.\n- **Concise API**: Simple and easy-to-use for handling HTTP requests.\n\n## Usage\n\n```typescript\n// Create an instance of Nixify with predefined services\nconst http = Nixify.create({\n  github: {\n    url: \"https://api.github.com\",\n    headers: {\n      \"x-API-KEY\": \"[TOKEN]\",\n    },\n  },\n  gitlab: {\n    url: \"https://gitlab.com/api/v4\",\n\tretryConfig: {\n\t\tretries: 4,\n\t\tretryOn: [400] // default statusCodes retryOn [408, 413, 429, 500, 502, 503, 504]\n\t\tretryDelay: 2000 // ms\n\t}\n\n  },\n});\n\n// Set headers for a specific service instance\nhttp.gitlab.setHeaders({ Authorization: `Bearer ${token}` });\n\n// Set headers globally\nhttp.setHeaders({ Authorization: `Bearer ${token}` });\n\n// Set headers before making a request for a specific service instance\nhttp.gitlab.beforeRequest((request, config) =\u003e {\n  // Modify request headers or perform other actions\n});\n\n// Set headers globally before making a request\nhttp.beforeRequest((request, config) =\u003e {\n  request.headers.set(\"Content-type\", \"application/json\");\n});\n\n// Will be called right after response\nhttp.gitlab.afterResponse((request, response config) =\u003e {});\nhttp.afterResponse((request, response config) =\u003e {});\n\n// Will be called right before retry\nhttp.beforeRetry((request, response, attempt, delay) =\u003e {});\nhttp.gitlab.beforeRetry((request, response, attempt, delay) =\u003e {});\n\n\n// Retry custom behavior\nconst { data, status } = await http.gitlab.get(\"/projects/:id/registry/repositories\", {\n\tparams: { id: 5645 } // /projects/5645/registry/repositories\n\tretry: {\n\t\tretryOn(attempt, response) {\n\t\t\t// Should stop retry by returning false\n\t\t\tif (attempt \u003e 3) return false\n\n\t\t\t// retry on 4xx or 5xx status codes\n\t\t\tif (response.status \u003e= 400) {\n\t\t\t\tconsole.log(`retrying, attempt number ${attempt + 1}`);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n}).json();\n\n// TypeScript Version\ninterface Repositories {}\nconst { data } = await http.gitlab.get\u003cRepositories\u003e(\"/search/repositories\").json();\n\n// Javascript Version\nconst { data, config } = await http\n  .get(\"https://api.github.com/search/repositories\", { headers: {} })\n  .json();\n\nconst { data, status } = await http.github.get(\"/search/repositories\").json();\n\n/**\n * If the body of the HTTP request is an instance of URLSearchParams,\n * The Content-Type is set automatically by `fetch`, \n * so we didn't have to explicit set it to 'application/x-www-form-urlencoded;charset=utf-8'.\n */\nconst searchParams = new URLSearchParams();\nsearchParams.set('food', 'sushi 🍣');\nsearchParams.set('drink', 'Bubble Tea 🧋');\n\nconst { data } = await http.post(path, { body: searchParams })\n\n/**\n * `fetch` automatically sets the Content-Type header,\n *  So we didn't have to explicit set it to 'multipart/form-data; boundary=---....'\n */\nconst formData = new FormData();\nformData.append('username', 'superAdmin');\nformData.append('password', 'admin1234');\n\nconst { data } = await http.post(path, { body: formData })\n\n/**\n * Cancellation\n */\nconst controller = new AbortController();\nconst { signal } = controller;\n\nsetTimeout(() =\u003e {\n\tcontroller.abort();\n}, 5000);\n\ntry {\n\tawait http.get(url, { signal }).text();\n} catch (error) {\n\tif (error.name === 'AbortError') {\n\t\tconsole.log('Fetch aborted');\n\t} else {\n\t\tconsole.error('Fetch error:', error);\n\t}\n}\n```\n\n## API DOCUMENTATION\n##### `Nixify.create(config: { [name: string]: Options }): ServiceReqMethods | RequestMethods`\n\nCreates an instance of Nixify with predefined service configurations.\n\n##### Parameters:\n\n- `config`: An object containing service configurations.\n\n##### Returns:\n\n- `NixifyInstance`: An instance of Nixify configured with the provided options.\n\n##### Example:\n\n```typescript\nconst http = Nixify.create({\n  github: {\n    url: \"https://api.github.com\",\n    headers: {\n      \"x-API-KEY\": \"[TOKEN]\",\n    },\n  },\n  gitlab: {\n    url: \"https://gitlab.com/api/v4/\",\n    headers: {},\n  },\n});\n```\n\n##### `Nixify.beforeRequest(fn: (request: Request, config: Options) =\u003e void)`\n##### `Nixify.{service}.beforeRequest(fn: (request: Request, config: Options) =\u003e void)`\nPrior to initiating a request for a particular service instance or globally, customize request headers or execute additional actions.\n\n##### Parameters:\n- `fn`: A callback function to be invoked right before a request.\n\t- `request`: A representation of the Request API, encapsulating HTTP configurations.\n\t- `config`: An object with `NixifyInstance` configurations.\n\n##### Example:\n\n```typescript\n// Set headers before making a request for a specific service instance\nhttp.gitlab.beforeRequest((request, config) =\u003e {\n  // Modify request headers or perform other actions\n});\n\n// Set headers globally before making a request\nhttp.beforeRequest((request, config) =\u003e {\n  request.headers.set(\"Content-type\", \"application/json\");\n});\n```\n##### `Nixify.afterResponse(fn: (request: Request, response: Response, config: Options) =\u003e void)`\n##### `Nixify.{service}.afterResponse(fn: (request: Request, response: Response config: Options) =\u003e void)`\n Still under development.\n\n##### Parameters:\n- `fn`: A callback function to be invoked right after a response.\n\t- `request`: A representation of the Request API, encapsulating HTTP configurations.\n\t- `response`: A representation of the Response API.\n\t- `config`: An object with `NixifyInstance` configurations.\n\n##### Example:\n\n```typescript\nhttp.gitlab.afterResponse((request, config) =\u003e {});\nhttp.afterResponse((request, config) =\u003e {});\n```\n##### `Nixify.beforeRetry(fn: (request: Request, response: Response, attempt: number, delay: number) =\u003e void)`\n##### `Nixify.{service}.beforeRetry(fn: (request: Request, response: Response, attempt: number, delay: number) =\u003e void)`\n\nRegisters a function to be executed before a fetch retry attempt within the Nixify service.\n\n#### Parameters:\n\n- `fn`: A callback function to be invoked before a retry attempt.\n  - `request`: A representation of the Request API, encapsulating HTTP configurations.\n  - `response`: A representation of the Response API.\n  - `attempt`: The number of the retry attempt.\n  - `delay`: The delay before the next retry attempt.\n\n#### Example:\n\n```typescript\nhttp.beforeRetry((request, response, attempt, delay) =\u003e {\n  if(response.status === 401) {\n\tconst { data } = await http.get(\"/refresh-token\").json()\n\n\trequest.headers.set(\"X-API-KEY\", data.token)\n  }\n});\n\nhttp.{service}.beforeRetry((request, response, attempt, delay) =\u003e {\n  // Your logic here\n});\n```\n\nThis method allows you to register a callback function that will be called before each retry attempt within the Nixify service. The callback function receives information about the request, response, the current attempt number, and the delay before the next retry.\n\n##### `Nixify.setHeaders(headers: { [key: string]: string })`\n##### `Nixify.{service}.setHeaders(headers: { [key: string]: string })`\nBefore making a request for a specific service instance or globally, modify request headers.\n\n##### Parameters:\n\n- `headers`: An object containing headers.\n\n##### Example:\n\n```typescript\n// Set headers for a specific service instance\nhttp.gitlab.setHeaders({ Authorization: `Bearer ${token}` });\n\n// Set headers globally\nhttp.setHeaders({ Authorization: `Bearer ${token}` });\n```\n\n#### Request method aliases\n\n```typescript\n// We provided supported for all request methods.\nhttp.get\u003cT\u003e(url | path, options?) // Returns an Object of callable type-setters methods.\n// instead of `responseType`.\n  json() // By default\n  text()\n  blob()\n  arrayBuffer()\n  formData()\nhttp.delete(url | path, options?)\n\nhttp.head(url | path, options?)\n\nhttp.options(url | path, options?)\n\nhttp.post(url[, body or json])\n\nhttp.put(url[, body or json])\n\nhttp.patch(url[, body or json])\n```\n\n##### Request Config\n\n\n```typescript\n// These are the available `options?` for making requests. Only the url is required.\ninterface Options {\n  url: string\n  headers?: { [key: string]: string }\n  hooks?: {\n\tbeforeRequest: (request: Request) =\u003e void\n\tafterResponse: (request: Request, response: Response, config: any) =\u003e void\n\tbeforeRetry: (request: Request, response: Response, attempt: number, delay: number) =\u003e void\n  }\n  qs?: {\n\treadonly strict?: boolean\n\treadonly encode?: boolean\n\treadonly arrayFormat?:\n\t\t| \"bracket\"\n\t\t| \"index\"\n\t\t| \"comma\"\n\t\t| \"separator\"\n\t\t| \"bracket-separator\"\n\t\t| \"colon-list-separator\"\n\t\t| \"none\"\n\treadonly arrayFormatSeparator?: string\n\treadonly sort?: ((itemLeft: string, itemRight: string) =\u003e number) | false\n\treadonly skipNull?: boolean\n\treadonly skipEmptyString?: boolean\n  }\n  timeout?: number | false\n  retryConfig?: {\n\tretries?: number | boolean\n\tretryDelay?: number | (attempt: number, response: Response | null) =\u003e number\n\tretryOn?: number[] | (attempt: number, response: Response | null) =\u003e boolean | Promise\u003cboolean\u003e \n  }\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/API/Request/Request#options\ninterface MethodConfig extends Omit\u003cRequestInit, \"method\"\u003e {\n  // URL parameters to be sent with the request\n  // (e.g http.get(path, { qs: { name: \"Joe\" } }) = path?name=Joe )\n  qs?: { [name: string]: string | URLSearchParams | Record\u003cstring, string\u003e | string[][] }\n  // \"/groups/:id/registry/repositories\" - { id: 4873 }\n  // \"/groups/4873/registry/repositories\"\n  params?: { [key: string]: string | number }\n  // `headers` are custom headers to be sent.\n  headers?: Object;\n  // `json` to send body as Content-Type JSON.\n  json?: Object;\n  //  `body` to send data under one of these types -\n  body?:\n    | Blob\n    | BufferSource\n    | FormData\n    | URLSearchParams\n    | USVString\n    | ReadableStream;\n  // `responseType` indicates the type of data that the server will respond with.\n  responseType?: \"json\" | \"text\" | \"blob\" | \"arrayBuffer\" | \"formData\";\n  timeout?: number | false\n  retry?: {\n\tretries?: number | boolean\n\tretryDelay?: number | (attempt: number, response: Response | null) =\u003e number\n\tretryOn?: number[] | (attempt: number, response: Response | null) =\u003e boolean | Promise\u003cboolean\u003e \n  }\n  // To cancel request using AbortController\n  signal?: AbortController;\n}\n```\n\n### Response Schema\n\nThe response for a request contains the following information.\n\n```typescript\ninterface ResponseInterface\u003cT\u003e {\n  // `data` is the response that was provided by the server\n  data: T;\n  // `headers` the HTTP headers that the server responded with\n  // All header names are lower cased and can be accessed using the bracket notation.\n  // Example: `response.headers['content-type']`\n  headers: Headers;\n  // `status` is the HTTP status code from the server response\n  status: number;\n  // `statusText` is the HTTP status message from the server response\n  statusText: string;\n  // `config` is the config that was provided to the request\n  config: Request;\n}\n```\n\n## Contributing\n\nWe welcome contributions! Feel free to open issues, submit pull requests, or provide feedback. Make sure to follow our [contribution guidelines](CONTRIBUTING.md).\n\n\n## Authors\n- [@Omar Chadidi](https://github.com/FxOmar) ❤️\n\n## License\n\nThis library is licensed under the [MIT License](LICENSE).\n","funding_links":[],"categories":["Uncategorized"],"sub_categories":["Uncategorized"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FFxOmar%2FNixify","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FFxOmar%2FNixify","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FFxOmar%2FNixify/lists"}