├── .github └── workflows │ └── main.yml ├── .gitignore ├── LICENSE ├── README.md ├── package.json ├── src ├── index.ts ├── types.ts └── utils.ts ├── tsconfig.json └── yarn.lock /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: [push] 3 | jobs: 4 | build: 5 | runs-on: ubuntu-latest 6 | 7 | steps: 8 | - name: Begin CI... 9 | uses: actions/checkout@v2 10 | 11 | - name: Use Node 12 12 | uses: actions/setup-node@v1 13 | with: 14 | node-version: 12.x 15 | 16 | - name: Use cached node_modules 17 | uses: actions/cache@v2 18 | with: 19 | path: node_modules 20 | key: nodeModules-${{ hashFiles('**/yarn.lock') }} 21 | restore-keys: | 22 | nodeModules- 23 | 24 | - name: Install dependencies 25 | run: yarn install --frozen-lockfile 26 | env: 27 | CI: true 28 | 29 | - name: Lint 30 | run: yarn lint 31 | env: 32 | CI: true 33 | 34 | - name: Test 35 | run: yarn test --ci --coverage --maxWorkers=2 36 | env: 37 | CI: true 38 | 39 | - name: Build 40 | run: yarn build 41 | env: 42 | CI: true 43 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.log 2 | .DS_Store 3 | node_modules 4 | dist 5 | .idea 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 doasync 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![DoAsync logo](https://leonardo.osnova.io/cf1dd2d1-f854-97b5-4707-406bcbf0d69c) 2 | 3 | [![NPM Version][npm-image]][npm-url] ![NPM Downloads][downloads-image] [![GitHub issues][issues-image]][issues-url] 4 | 5 | [npm-image]: https://img.shields.io/npm/v/fry.svg 6 | [npm-url]: https://www.npmjs.com/package/fry 7 | [downloads-image]: https://img.shields.io/npm/dw/fry.svg 8 | [deps-image]: https://david-dm.org/doasync/fry.svg 9 | [issues-image]: https://img.shields.io/github/issues/doasync/fry.svg 10 | [issues-url]: https://github.com/doasync/fry/issues 11 | 12 | # Benefits over plain `fetch` 13 | 14 | - Extended API 15 | - Treats non-2xx status codes as errors 16 | - Handles JSON 17 | - Custom defaults 18 | - Easy interceptors 19 | - Transform function 20 | - And more... 21 | 22 | > `fry` is written in TypeScript 23 | 24 | --- 25 | 26 | ## Installation 27 | 28 | ```bash 29 | npm install fry 30 | ``` 31 | 32 | ## Description 33 | 34 | fry is `fetch` on steroids :) 35 | 36 | There are two exports in the package: `request` and `createRequest` 37 | 38 | `createRequest` is used to create a `request` with predefined config 39 | 40 | The `request` accepts the same params/options as `fetch` as well as additional ones: baseUrl, url, data, params, fn, silent 41 | 42 | ```md 43 | url - the only required param, 44 | baseUrl - will be prepended to url, 45 | data - object for json body, 46 | params - query as an object, 47 | silent - do not fall on http errors, 48 | fn - preparation of the result (if necessary) 49 | ``` 50 | 51 | `fn` parameters: 52 | 53 | ```md 54 | request - object of the request, 55 | response - object of the response, 56 | jsonData - parsed json, 57 | config - what was passed to the request 58 | ``` 59 | 60 | There are also basic inteceptors: 61 | 62 | ```md 63 | onBeforeRequest - change config, 64 | onRequestError - return a new response (or rethrow an error), 65 | onBeforeResponse - do something before response is handled, 66 | onResponseError - return a new response or handle errors, 67 | ``` 68 | 69 | ## Usage 70 | 71 | ```typescript 72 | import { createRequest } from 'fry'; // import { request } from "fry"; 73 | 74 | const request = createRequest({ 75 | baseUrl: 'https://app.io/api', 76 | redirect: 'error', 77 | }); 78 | 79 | export const checkUser = id => 80 | request({ 81 | url: 'user', 82 | method: 'post', 83 | data: { userId: id }, // json 84 | fn: ({ jsonData: [user], config }) => 85 | Boolean(config.data.userId === user.id && user.exists === true), // return boolean 86 | }); 87 | 88 | // No need for async / await 89 | export const submitTransaction = tx => 90 | request({ 91 | url: 'transactions', 92 | method: 'post', 93 | data: { base64 }, 94 | fn: ({ config, request, response, jsonData, resource, init, baseConfig }) => 95 | tx, // returns tx 96 | }); 97 | 98 | export const activate = accountId => 99 | request({ 100 | url: `accounts/${accountId}`, 101 | method: 'post', 102 | }); // returns jsonData if no `fn` 103 | 104 | const getAccount = accountId => request(`accounts/${accountId}`); // 'get' method is default 105 | 106 | // Using TypeScript 107 | 108 | const fetchCountry = async countryId => 109 | request(`api/countries/${countryId}`) as Promise; 110 | 111 | const fetchLocations = async () => 112 | request({ 113 | url: 'api/locations/countries/', 114 | fn: ({ jsonData }) => convertCountriesToLocations(jsonData as Country[]), 115 | }); 116 | ``` 117 | 118 | ### Types 119 | 120 |
121 | 122 | Config 123 | 124 | 125 | ```ts 126 | export type Config = { 127 | url?: Url; 128 | baseUrl?: BaseUrl; 129 | params?: Params; 130 | data?: Json; 131 | fn?: Fn; 132 | silent?: boolean; 133 | onBeforeRequest?: (config: Config) => Config | Promise>; 134 | onRequestError?: (meta: { 135 | config: Config; 136 | request: Request; 137 | error: unknown; 138 | }) => Response | Promise; 139 | onBeforeResponse?: (meta: { 140 | config: Config; 141 | response: Response; 142 | request: Request; 143 | }) => Response | Promise; 144 | onResponseError?: (meta: { 145 | config: Config; 146 | response: Response; 147 | request: Request; 148 | error: Error; 149 | }) => Response | Promise; 150 | } & RequestInit; 151 | ``` 152 | 153 |
154 | 155 |
156 | 157 | Other 158 | 159 | 160 | ```ts 161 | export type Json = JsonPrimitive | JsonObject | JsonArray; 162 | export type JsonPrimitive = string | number | boolean | null; 163 | export type JsonObject = { [key: string]: Json }; 164 | export type JsonArray = Json[]; 165 | 166 | export type ObjectString = { [key: string]: string }; 167 | 168 | export type Params = string[][] | ObjectString | string | URLSearchParams; 169 | export type Url = string; 170 | export type BaseUrl = string; 171 | 172 | export type Fn = (meta: { 173 | config: ConfigFn; 174 | request: Request; 175 | response: Response; 176 | jsonData?: unknown; 177 | }) => R; 178 | ``` 179 | 180 |
181 | 182 | ### Repository 183 | 184 | --- 185 | 186 | GitHub ★: https://github.com/doasync/fry 187 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "fry", 3 | "version": "2.3.0", 4 | "author": "doasync ", 5 | "license": "MIT", 6 | "description": "Tiny declarative HTTP client based on the browser Fetch API", 7 | "repository": { 8 | "type": "git", 9 | "url": "https://github.com/doasync/fry.git" 10 | }, 11 | "main": "dist/index.js", 12 | "typings": "dist/index.d.ts", 13 | "files": [ 14 | "dist", 15 | "src" 16 | ], 17 | "engines": { 18 | "node": ">=10" 19 | }, 20 | "scripts": { 21 | "start": "tsdx watch", 22 | "build": "tsdx build", 23 | "test": "tsdx test --passWithNoTests", 24 | "lint": "tsdx lint", 25 | "prepare": "tsdx build" 26 | }, 27 | "peerDependencies": {}, 28 | "husky": { 29 | "hooks": { 30 | "pre-commit": "tsdx lint" 31 | } 32 | }, 33 | "prettier": { 34 | "printWidth": 80, 35 | "semi": true, 36 | "singleQuote": true, 37 | "trailingComma": "es5" 38 | }, 39 | "module": "dist/fry.esm.js", 40 | "devDependencies": { 41 | "husky": "^4.2.5", 42 | "tsdx": "^0.13.3", 43 | "tslib": "^2.0.1", 44 | "typescript": "^4.0.2" 45 | }, 46 | "keywords": [ 47 | "fetch", 48 | "request", 49 | "requests", 50 | "http", 51 | "https", 52 | "fetching", 53 | "get", 54 | "url", 55 | "curl", 56 | "wget", 57 | "net", 58 | "network", 59 | "ajax", 60 | "api", 61 | "rest", 62 | "xhr", 63 | "browser", 64 | "got", 65 | "axios", 66 | "node-fetch" 67 | ] 68 | } 69 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import { Config, ConfigFn, ConfigNoFn, Url } from './types'; 2 | import { getJson, getResource } from './utils'; 3 | 4 | const RESPONSE_ERROR = 'ResponseError'; 5 | 6 | export const isResponseError = (error: Error): boolean => 7 | error.name === RESPONSE_ERROR; 8 | 9 | const contentTypeJson = { 'Content-Type': 'application/json' }; 10 | 11 | export const createRequest = < 12 | T = unknown, 13 | BaseConfig extends ConfigFn | ConfigNoFn = ConfigFn | ConfigNoFn 14 | >( 15 | baseConfig?: BaseConfig 16 | ): { 17 | (customConfig: ConfigFn): Promise; 18 | (customConfig: ConfigNoFn | Url): Promise< 19 | BaseConfig extends ConfigFn ? X : R2 20 | >; 21 | } => async ( 22 | customConfig: ConfigFn | ConfigNoFn | Url 23 | ): Promise ? X : R) | undefined> => { 24 | if (typeof customConfig === 'string') { 25 | customConfig = { url: customConfig }; 26 | } 27 | 28 | let initPromise = Promise.resolve(); 29 | let config = { ...baseConfig, ...customConfig } as Config; 30 | 31 | if (config.onBeforeRequest) { 32 | try { 33 | config = await config.onBeforeRequest({ config }); 34 | } catch (error) { 35 | initPromise = Promise.reject(error); 36 | } 37 | } 38 | 39 | const { 40 | url, 41 | baseUrl, 42 | params, 43 | data, 44 | fn, 45 | silent, 46 | onBeforeRequest, 47 | onRequestError, 48 | onBeforeResponse, 49 | onResponseError, 50 | ...init 51 | } = config; 52 | 53 | if (data) { 54 | Object.assign(init, { 55 | headers: { ...contentTypeJson, ...init.headers }, 56 | body: JSON.stringify(data), 57 | }); 58 | } 59 | 60 | const request = new Request(getResource({ url, baseUrl, params }), init); 61 | 62 | const handleResponseErrors = async (response: Response) => { 63 | if (!response.ok) { 64 | const error = new Error(response.statusText); 65 | error.name = RESPONSE_ERROR; 66 | 67 | if (onResponseError) { 68 | return onResponseError({ config, request, response, error }); 69 | } 70 | 71 | return Promise.reject(error); 72 | } 73 | 74 | return response; 75 | }; 76 | 77 | let promise = initPromise.then(async () => fetch(request)); 78 | 79 | if (onRequestError) { 80 | promise = promise.catch((error: unknown) => { 81 | return onRequestError({ config, request, error }); 82 | }); 83 | } 84 | 85 | if (onBeforeResponse) { 86 | promise = promise.then(response => { 87 | return onBeforeResponse({ config, request, response }); 88 | }); 89 | } 90 | 91 | if (!silent) { 92 | promise = promise.then(handleResponseErrors); 93 | } 94 | 95 | return promise.then(async response => { 96 | const jsonData = await getJson(response); 97 | return fn 98 | ? fn({ 99 | config: config as ConfigFn, 100 | request, 101 | response, 102 | jsonData, 103 | }) 104 | : jsonData; 105 | }); 106 | }; 107 | 108 | export const request = createRequest(); 109 | export const fry = createRequest(); 110 | -------------------------------------------------------------------------------- /src/types.ts: -------------------------------------------------------------------------------- 1 | export type Json = JsonPrimitive | JsonObject | JsonArray; 2 | export type JsonPrimitive = string | number | boolean | null; 3 | export type JsonObject = { [key: string]: Json }; 4 | export type JsonArray = Json[]; 5 | 6 | export interface ObjectString { 7 | [key: string]: string; 8 | } 9 | 10 | export type Params = ObjectString | string | URLSearchParams; 11 | export type Url = string; 12 | export type BaseUrl = string; 13 | export type Fn = (meta: { 14 | config: ConfigFn; 15 | request: Request; 16 | response: Response; 17 | jsonData?: unknown; 18 | }) => R; 19 | 20 | export interface Config extends ConfigNoFn { 21 | fn?: Fn; 22 | } 23 | 24 | export interface ConfigFn extends ConfigNoFn { 25 | fn: Fn; 26 | } 27 | 28 | export interface ConfigNoFn extends RequestInit { 29 | url?: Url; 30 | baseUrl?: BaseUrl; 31 | params?: Params; 32 | data?: Json; 33 | silent?: boolean; 34 | onBeforeRequest?: OnBeforeRequest; 35 | onRequestError?: OnRequestError; 36 | onBeforeResponse?: OnBeforeResponse; 37 | onResponseError?: OnResponseError; 38 | } 39 | 40 | export type OnBeforeRequest = (meta: { 41 | config: Config; 42 | }) => Config | Promise>; 43 | 44 | export type OnRequestError = (meta: { 45 | config: Config; 46 | request: Request; 47 | error: unknown; 48 | }) => Response | Promise; 49 | 50 | export type OnBeforeResponse = (meta: { 51 | config: Config; 52 | response: Response; 53 | request: Request; 54 | }) => Response | Promise; 55 | 56 | export type OnResponseError = (meta: { 57 | config: Config; 58 | response: Response; 59 | request: Request; 60 | error: Error; 61 | }) => Response | Promise; 62 | -------------------------------------------------------------------------------- /src/utils.ts: -------------------------------------------------------------------------------- 1 | import { BaseUrl, Params, Url } from './types'; 2 | 3 | export const getQueryString = (params: Params): string => { 4 | const qs = String(new URLSearchParams(params)); 5 | return qs && `?${qs}`; 6 | }; 7 | 8 | export const getResource = ({ 9 | url, 10 | baseUrl, 11 | params, 12 | }: { 13 | url?: Url; 14 | baseUrl?: BaseUrl; 15 | params?: Params; 16 | }): string => { 17 | const qs = params ? getQueryString(params) : ''; 18 | if (baseUrl && url) { 19 | return `${baseUrl.replace(/\/$/, '')}/${url.replace(/^\//, '')}${qs}`; 20 | } 21 | return `${baseUrl ?? url ?? ''}${qs}`; 22 | }; 23 | 24 | export const getJson = async ( 25 | response: Response 26 | ): Promise => { 27 | try { 28 | return (await response.json()) as T; 29 | } catch { 30 | return undefined; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "include": ["src", "types"], 3 | "compilerOptions": { 4 | "module": "esnext", 5 | "target": "es2017", 6 | "lib": ["dom", "esnext"], 7 | "importHelpers": true, 8 | "declaration": true, 9 | "sourceMap": true, 10 | "rootDir": "./src", 11 | "strict": true, 12 | "noUnusedLocals": true, 13 | "noUnusedParameters": true, 14 | "noImplicitReturns": true, 15 | "noFallthroughCasesInSwitch": true, 16 | "moduleResolution": "node", 17 | "esModuleInterop": true 18 | } 19 | } 20 | --------------------------------------------------------------------------------