Compare commits
55 Commits
Author | SHA1 | Date |
---|---|---|
Dmitriy Pleshevskiy | 56af2e57aa | |
Dmitriy Pleshevskiy | 0f34ac9182 | |
Dmitriy Pleshevskiy | 163822a49f | |
Dmitriy Pleshevskiy | 39d80815c9 | |
Dmitriy Pleshevskiy | 1a8ed09d85 | |
Dmitriy Pleshevskiy | f109d87b41 | |
Dmitriy Pleshevskiy | 807493a5e3 | |
Dmitriy Pleshevskiy | acddd23634 | |
Dmitriy Pleshevskiy | 3c1582ef9f | |
Dmitriy Pleshevskiy | 3d8898f333 | |
Dmitriy Pleshevskiy | 4ddc6fb420 | |
Dmitriy Pleshevskiy | 6249d0bde9 | |
Dmitriy Pleshevskiy | 00308d6718 | |
Dmitriy Pleshevskiy | 304611fb53 | |
Dmitriy Pleshevskiy | a1193cee47 | |
Dmitriy Pleshevskiy | b4a3d79b6a | |
Dmitriy Pleshevskiy | c43df16fef | |
Dmitriy Pleshevskiy | 0ea4541618 | |
Dmitriy Pleshevskiy | f4bfa34466 | |
Dmitriy Pleshevskiy | 7683c20a2e | |
Dmitriy Pleshevskiy | 68d379d3c5 | |
Dmitriy Pleshevskiy | 7df0c94f3e | |
Dmitriy Pleshevskiy | edc88a64ff | |
Dmitriy Pleshevskiy | e762303d04 | |
Dmitriy Pleshevskiy | beba6445a2 | |
Dmitriy Pleshevskiy | 79b404cd28 | |
Dmitriy Pleshevskiy | a7d045d180 | |
Dmitriy Pleshevskiy | 83605adee1 | |
Dmitriy Pleshevskiy | e0dd752b9a | |
Dmitriy Pleshevskiy | 70da8b3ad0 | |
Dmitriy Pleshevskiy | a1afb6b599 | |
Dmitriy Pleshevskiy | d4e83748c3 | |
Dmitriy Pleshevskiy | 651e09bc31 | |
Dmitriy Pleshevskiy | 96c7ea554c | |
Dmitriy Pleshevskiy | 8a87c9af14 | |
Dmitriy Pleshevskiy | 49aac94675 | |
Dmitriy Pleshevskiy | 817b8e46ad | |
Dmitriy Pleshevskiy | 0c3cb11c13 | |
Dmitriy Pleshevskiy | fd7e7c7585 | |
Dmitriy Pleshevskiy | c848b0c785 | |
Dmitriy Pleshevskiy | b944725e07 | |
Dmitriy Pleshevskiy | 078b5c1a3a | |
Dmitriy Pleshevskiy | 4795bb3cbc | |
Dmitriy Pleshevskiy | 1eafe8bc44 | |
Dmitriy Pleshevskiy | be9f9b6da3 | |
Dmitriy Pleshevskiy | cf2bc7f917 | |
Dmitriy Pleshevskiy | a46dc77297 | |
Dmitriy Pleshevskiy | 7457fc1b75 | |
Dmitriy Pleshevskiy | e812d4e077 | |
Dmitriy Pleshevskiy | e3a0989944 | |
Dmitriy Pleshevskiy | cf61435259 | |
Dmitriy Pleshevskiy | a66e10fc1a | |
Dmitriy Pleshevskiy | e303485f58 | |
Dmitriy Pleshevskiy | 132ae5c22c | |
Dmitriy Pleshevskiy | d2c99a578b |
|
@ -0,0 +1,36 @@
|
|||
---
|
||||
name: Bug report
|
||||
about: Create a report to help us improve
|
||||
title: ''
|
||||
labels: bug
|
||||
assignees: pleshevskiy
|
||||
|
||||
---
|
||||
|
||||
<!-- Describe the bug -->
|
||||
A clear and concise description of what the bug is.
|
||||
|
||||
### Steps to reproduce
|
||||
1. ...
|
||||
|
||||
```typescript
|
||||
// Paste a minimal example that causes the problem.
|
||||
```
|
||||
|
||||
### Expected Behavior
|
||||
<!-- Tell us what should happen. -->
|
||||
|
||||
|
||||
### Actual Behavior
|
||||
<!-- Tell us what happens instead. -->
|
||||
|
||||
```
|
||||
Paste the full traceback if there was an exception.
|
||||
```
|
||||
|
||||
### Environment
|
||||
|
||||
* OS:
|
||||
* node.js version:
|
||||
* react version:
|
||||
* react-rest-request version:
|
|
@ -0,0 +1,20 @@
|
|||
---
|
||||
name: Feature request
|
||||
about: Suggest an idea for this project
|
||||
title: ''
|
||||
labels: enhancement
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Is your feature request related to a problem? Please describe.**
|
||||
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
|
||||
|
||||
**Describe the solution you'd like**
|
||||
A clear and concise description of what you want to happen.
|
||||
|
||||
**Describe alternatives you've considered**
|
||||
A clear and concise description of any alternative solutions or features you've considered.
|
||||
|
||||
**Additional context**
|
||||
Add any other context or screenshots about the feature request here.
|
|
@ -8,12 +8,11 @@
|
|||
/coverage
|
||||
|
||||
# production
|
||||
/target
|
||||
/public
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
.env
|
||||
/.env
|
||||
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
|
|
|
@ -0,0 +1,129 @@
|
|||
|
||||
# Contributor Covenant Code of Conduct
|
||||
|
||||
## Our Pledge
|
||||
|
||||
We as members, contributors, and leaders pledge to make participation in our
|
||||
community a harassment-free experience for everyone, regardless of age, body
|
||||
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
||||
identity and expression, level of experience, education, socio-economic status,
|
||||
nationality, personal appearance, race, religion, or sexual identity
|
||||
and orientation.
|
||||
|
||||
We pledge to act and interact in ways that contribute to an open, welcoming,
|
||||
diverse, inclusive, and healthy community.
|
||||
|
||||
## Our Standards
|
||||
|
||||
Examples of behavior that contributes to a positive environment for our
|
||||
community include:
|
||||
|
||||
* Demonstrating empathy and kindness toward other people
|
||||
* Being respectful of differing opinions, viewpoints, and experiences
|
||||
* Giving and gracefully accepting constructive feedback
|
||||
* Accepting responsibility and apologizing to those affected by our mistakes,
|
||||
and learning from the experience
|
||||
* Focusing on what is best not just for us as individuals, but for the
|
||||
overall community
|
||||
|
||||
Examples of unacceptable behavior include:
|
||||
|
||||
* The use of sexualized language or imagery, and sexual attention or
|
||||
advances of any kind
|
||||
* Trolling, insulting or derogatory comments, and personal or political attacks
|
||||
* Public or private harassment
|
||||
* Publishing others' private information, such as a physical or email
|
||||
address, without their explicit permission
|
||||
* Other conduct which could reasonably be considered inappropriate in a
|
||||
professional setting
|
||||
|
||||
## Enforcement Responsibilities
|
||||
|
||||
Community leaders are responsible for clarifying and enforcing our standards of
|
||||
acceptable behavior and will take appropriate and fair corrective action in
|
||||
response to any behavior that they deem inappropriate, threatening, offensive,
|
||||
or harmful.
|
||||
|
||||
Community leaders have the right and responsibility to remove, edit, or reject
|
||||
comments, commits, code, wiki edits, issues, and other contributions that are
|
||||
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
||||
decisions when appropriate.
|
||||
|
||||
## Scope
|
||||
|
||||
This Code of Conduct applies within all community spaces, and also applies when
|
||||
an individual is officially representing the community in public spaces.
|
||||
Examples of representing our community include using an official e-mail address,
|
||||
posting via an official social media account, or acting as an appointed
|
||||
representative at an online or offline event.
|
||||
|
||||
## Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||
reported to the community leaders responsible for enforcement at:
|
||||
dmitriy@ideascup.me.
|
||||
All complaints will be reviewed and investigated promptly and fairly.
|
||||
|
||||
All community leaders are obligated to respect the privacy and security of the
|
||||
reporter of any incident.
|
||||
|
||||
## Enforcement Guidelines
|
||||
|
||||
Community leaders will follow these Community Impact Guidelines in determining
|
||||
the consequences for any action they deem in violation of this Code of Conduct:
|
||||
|
||||
### 1. Correction
|
||||
|
||||
**Community Impact**: Use of inappropriate language or other behavior deemed
|
||||
unprofessional or unwelcome in the community.
|
||||
|
||||
**Consequence**: A private, written warning from community leaders, providing
|
||||
clarity around the nature of the violation and an explanation of why the
|
||||
behavior was inappropriate. A public apology may be requested.
|
||||
|
||||
### 2. Warning
|
||||
|
||||
**Community Impact**: A violation through a single incident or series
|
||||
of actions.
|
||||
|
||||
**Consequence**: A warning with consequences for continued behavior. No
|
||||
interaction with the people involved, including unsolicited interaction with
|
||||
those enforcing the Code of Conduct, for a specified period of time. This
|
||||
includes avoiding interactions in community spaces as well as external channels
|
||||
like social media. Violating these terms may lead to a temporary or
|
||||
permanent ban.
|
||||
|
||||
### 3. Temporary Ban
|
||||
|
||||
**Community Impact**: A serious violation of community standards, including
|
||||
sustained inappropriate behavior.
|
||||
|
||||
**Consequence**: A temporary ban from any sort of interaction or public
|
||||
communication with the community for a specified period of time. No public or
|
||||
private interaction with the people involved, including unsolicited interaction
|
||||
with those enforcing the Code of Conduct, is allowed during this period.
|
||||
Violating these terms may lead to a permanent ban.
|
||||
|
||||
### 4. Permanent Ban
|
||||
|
||||
**Community Impact**: Demonstrating a pattern of violation of community
|
||||
standards, including sustained inappropriate behavior, harassment of an
|
||||
individual, or aggression toward or disparagement of classes of individuals.
|
||||
|
||||
**Consequence**: A permanent ban from any sort of public interaction within
|
||||
the community.
|
||||
|
||||
## Attribution
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
||||
version 2.0, available at
|
||||
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
|
||||
|
||||
Community Impact Guidelines were inspired by [Mozilla's code of conduct
|
||||
enforcement ladder](https://github.com/mozilla/diversity).
|
||||
|
||||
[homepage]: https://www.contributor-covenant.org
|
||||
|
||||
For answers to common questions about this code of conduct, see the FAQ at
|
||||
https://www.contributor-covenant.org/faq. Translations are available at
|
||||
https://www.contributor-covenant.org/translations.
|
|
@ -0,0 +1,10 @@
|
|||
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright © 2020 Dmitriy Pleshevskiy
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
60
README.md
60
README.md
|
@ -1,6 +1,6 @@
|
|||
# react-rest-request
|
||||
|
||||
Minimalistic REST API client for React inspired by Apollo.
|
||||
Minimalist REST API client for React inspired by Apollo.
|
||||
|
||||
|
||||
# Installation
|
||||
|
@ -28,7 +28,7 @@ type Movie = Readonly<{
|
|||
imdbId: string;
|
||||
}>
|
||||
|
||||
const MoviesEndpoint: Endpoint = {
|
||||
const MoviesEndpoint: Endpoint<MoviesResponse, void> = {
|
||||
method: Method.GET,
|
||||
url: '/action-adventure',
|
||||
};
|
||||
|
@ -36,14 +36,7 @@ const MoviesEndpoint: Endpoint = {
|
|||
type MoviesResponse = Movie[];
|
||||
|
||||
function App() {
|
||||
const [movies, { data, loading }] = useRequest<MoviesResponse>(MoviesEndpoint);
|
||||
|
||||
React.useEffect(
|
||||
() => {
|
||||
movies();
|
||||
},
|
||||
[movies]
|
||||
);
|
||||
const { data, loading } = useRequest(MoviesEndpoint);
|
||||
|
||||
return !data ? (
|
||||
<div>{ loading ? 'Loading...' : 'Something went wrong' }</div>
|
||||
|
@ -63,3 +56,50 @@ ReactDOM.render(
|
|||
document.getElementById('root'),
|
||||
);
|
||||
```
|
||||
|
||||
# Features
|
||||
|
||||
- [x] Automatic and lazy requests.
|
||||
- [x] Transform response data.
|
||||
- [x] Simple refetch of a previous request.
|
||||
- [x] Automatic and manual cancellation of the request.
|
||||
- [ ] Cache request responses.
|
||||
|
||||
|
||||
### Transform response
|
||||
|
||||
If you have an endpoint that doesn't fit into your beautiful architecture
|
||||
with its response data, you can transform the response before it's written
|
||||
to the state.
|
||||
|
||||
```typescript
|
||||
import { Endpoint, Method } from 'react-rest-request';
|
||||
|
||||
export type Movie = Readonly<{
|
||||
id: number;
|
||||
title: string;
|
||||
posterURL: string;
|
||||
imdbId: string;
|
||||
}>
|
||||
|
||||
export const MoviesEndpoint: Endpoint<MoviesResponse, void> = {
|
||||
method: Method.GET,
|
||||
url: '/action-adventure',
|
||||
transformResponseData(data: Movie[]) {
|
||||
return {
|
||||
items: data,
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export type MoviesResponse = {
|
||||
items: Movie[],
|
||||
}
|
||||
```
|
||||
|
||||
# License
|
||||
|
||||
Released under the [MIT License].
|
||||
|
||||
|
||||
[MIT License]: https://github.com/pleshevskiy/react-rest-request/blob/master/LICENSE.md
|
||||
|
|
|
@ -0,0 +1 @@
|
|||
SKIP_PREFLIGHT_CHECK=true
|
|
@ -0,0 +1 @@
|
|||
[{"/home/janabhumi/sandbox/react-rest-request/examples/cancelation/src/index.tsx":"1","/home/janabhumi/sandbox/react-rest-request/examples/cancelation/src/app.tsx":"2","/home/janabhumi/sandbox/react-rest-request/examples/cancelation/src/pages.tsx":"3","/home/janabhumi/sandbox/react-rest-request/examples/cancelation/src/endpoint.ts":"4"},{"size":389,"mtime":1608684208907,"results":"5","hashOfConfig":"6"},{"size":485,"mtime":1608684628086,"results":"7","hashOfConfig":"6"},{"size":894,"mtime":1608689496251,"results":"8","hashOfConfig":"6"},{"size":285,"mtime":1608684386674,"results":"9","hashOfConfig":"6"},{"filePath":"10","messages":"11","errorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0,"usedDeprecatedRules":"12"},"v1vt4k",{"filePath":"13","messages":"14","errorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0,"usedDeprecatedRules":"12"},{"filePath":"15","messages":"16","errorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"17","messages":"18","errorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0,"usedDeprecatedRules":"12"},"/home/janabhumi/sandbox/react-rest-request/examples/cancelation/src/index.tsx",[],["19","20"],"/home/janabhumi/sandbox/react-rest-request/examples/cancelation/src/app.tsx",[],"/home/janabhumi/sandbox/react-rest-request/examples/cancelation/src/pages.tsx",[],"/home/janabhumi/sandbox/react-rest-request/examples/cancelation/src/endpoint.ts",[],{"ruleId":"21","replacedBy":"22"},{"ruleId":"23","replacedBy":"24"},"no-native-reassign",["25"],"no-negated-in-lhs",["26"],"no-global-assign","no-unsafe-negation"]
|
|
@ -0,0 +1,23 @@
|
|||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||
|
||||
# dependencies
|
||||
/node_modules
|
||||
/.pnp
|
||||
.pnp.js
|
||||
|
||||
# testing
|
||||
/coverage
|
||||
|
||||
# production
|
||||
/build
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
.env.local
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
|
@ -0,0 +1,46 @@
|
|||
# Getting Started with Create React App
|
||||
|
||||
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
|
||||
|
||||
## Available Scripts
|
||||
|
||||
In the project directory, you can run:
|
||||
|
||||
### `npm start`
|
||||
|
||||
Runs the app in the development mode.\
|
||||
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
|
||||
|
||||
The page will reload if you make edits.\
|
||||
You will also see any lint errors in the console.
|
||||
|
||||
### `npm test`
|
||||
|
||||
Launches the test runner in the interactive watch mode.\
|
||||
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
|
||||
|
||||
### `npm run build`
|
||||
|
||||
Builds the app for production to the `build` folder.\
|
||||
It correctly bundles React in production mode and optimizes the build for the best performance.
|
||||
|
||||
The build is minified and the filenames include the hashes.\
|
||||
Your app is ready to be deployed!
|
||||
|
||||
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
|
||||
|
||||
### `npm run eject`
|
||||
|
||||
**Note: this is a one-way operation. Once you `eject`, you can’t go back!**
|
||||
|
||||
If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
|
||||
|
||||
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
|
||||
|
||||
You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
|
||||
|
||||
## Learn More
|
||||
|
||||
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
|
||||
|
||||
To learn React, check out the [React documentation](https://reactjs.org/).
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,48 @@
|
|||
{
|
||||
"name": "cancelation",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@testing-library/jest-dom": "^5.11.6",
|
||||
"@testing-library/react": "^11.2.2",
|
||||
"@testing-library/user-event": "^12.6.0",
|
||||
"@types/jest": "^26.0.19",
|
||||
"@types/node": "^12.19.9",
|
||||
"@types/react": "^16.14.2",
|
||||
"@types/react-dom": "^16.9.10",
|
||||
"react": "^17.0.1",
|
||||
"react-dom": "^17.0.1",
|
||||
"react-rest-request": "../../",
|
||||
"react-router-dom": "^5.2.0",
|
||||
"react-scripts": "4.0.1",
|
||||
"typescript": "^4.1.3",
|
||||
"web-vitals": "^0.2.4"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "react-scripts start",
|
||||
"build": "react-scripts build",
|
||||
"test": "react-scripts test",
|
||||
"eject": "react-scripts eject"
|
||||
},
|
||||
"eslintConfig": {
|
||||
"extends": [
|
||||
"react-app",
|
||||
"react-app/jest"
|
||||
]
|
||||
},
|
||||
"browserslist": {
|
||||
"production": [
|
||||
">0.2%",
|
||||
"not dead",
|
||||
"not op_mini all"
|
||||
],
|
||||
"development": [
|
||||
"last 1 chrome version",
|
||||
"last 1 firefox version",
|
||||
"last 1 safari version"
|
||||
]
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react-router-dom": "^5.1.6"
|
||||
}
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="theme-color" content="#000000" />
|
||||
<meta
|
||||
name="description"
|
||||
content="Web site created using create-react-app"
|
||||
/>
|
||||
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
|
||||
<!--
|
||||
manifest.json provides metadata used when your web app is installed on a
|
||||
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
|
||||
-->
|
||||
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
|
||||
<!--
|
||||
Notice the use of %PUBLIC_URL% in the tags above.
|
||||
It will be replaced with the URL of the `public` folder during the build.
|
||||
Only files inside the `public` folder can be referenced from the HTML.
|
||||
|
||||
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
|
||||
work correctly both with client-side routing and a non-root public URL.
|
||||
Learn how to configure a non-root public URL by running `npm run build`.
|
||||
-->
|
||||
<title>React App</title>
|
||||
</head>
|
||||
<body>
|
||||
<noscript>You need to enable JavaScript to run this app.</noscript>
|
||||
<div id="root"></div>
|
||||
<!--
|
||||
This HTML file is a template.
|
||||
If you open it directly in the browser, you will see an empty page.
|
||||
|
||||
You can add webfonts, meta tags, or analytics to this file.
|
||||
The build step will place the bundled scripts into the <body> tag.
|
||||
|
||||
To begin the development, run `npm start` or `yarn start`.
|
||||
To create a production bundle, use `npm run build` or `yarn build`.
|
||||
-->
|
||||
</body>
|
||||
</html>
|
|
@ -0,0 +1,19 @@
|
|||
import React from 'react';
|
||||
import { BrowserRouter, Route, Switch } from 'react-router-dom'
|
||||
import { DelayPage, MainPage } from './pages';
|
||||
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<BrowserRouter>
|
||||
<Switch>
|
||||
<Route exact path='/'>
|
||||
<MainPage />
|
||||
</Route>
|
||||
<Route exact path='/delay'>
|
||||
<DelayPage />
|
||||
</Route>
|
||||
</Switch>
|
||||
</BrowserRouter>
|
||||
)
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
import { Endpoint, Method } from 'react-rest-request';
|
||||
|
||||
export const DelayEndpoint: Endpoint<{ url: string}, void, { seconds: number }> = {
|
||||
method: Method.GET,
|
||||
url: ({ seconds }) => `/delay/${seconds}`,
|
||||
transformResponseData({ url }: any) {
|
||||
return { url }
|
||||
}
|
||||
};
|
|
@ -0,0 +1,17 @@
|
|||
import React from 'react';
|
||||
import ReactDOM from 'react-dom';
|
||||
import { RequestProvider, Client } from 'react-rest-request';
|
||||
import App from './app';
|
||||
|
||||
const client = new Client({
|
||||
baseUrl: 'https://httpbin.org',
|
||||
});
|
||||
|
||||
ReactDOM.render(
|
||||
<React.StrictMode>
|
||||
<RequestProvider client={client}>
|
||||
<App />
|
||||
</RequestProvider>
|
||||
</React.StrictMode>,
|
||||
document.getElementById('root')
|
||||
);
|
|
@ -0,0 +1,35 @@
|
|||
import React from 'react';
|
||||
import { useRequest } from 'react-rest-request';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { DelayEndpoint } from './endpoint';
|
||||
|
||||
|
||||
export function MainPage() {
|
||||
return <Link to='/delay'>Move to delay page</Link>
|
||||
}
|
||||
|
||||
export function DelayPage() {
|
||||
const { data, loading, cancel, isCanceled } = useRequest(
|
||||
DelayEndpoint,
|
||||
{
|
||||
params: {
|
||||
seconds: 10,
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div>
|
||||
<Link to='/'>Back to main page</Link>
|
||||
</div>
|
||||
{!data ? (
|
||||
<div>{ loading ? 'Loading...' : isCanceled ? 'Request was canceled' : 'Something went wrong' }</div>
|
||||
) : <div>Success</div>}
|
||||
|
||||
<button type='button' onClick={() => cancel() }>
|
||||
Cancel immediately!
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
/// <reference types="react-scripts" />
|
|
@ -0,0 +1,26 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
"target": "es5",
|
||||
"lib": [
|
||||
"dom",
|
||||
"dom.iterable",
|
||||
"esnext"
|
||||
],
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"esModuleInterop": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"strict": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "node",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx"
|
||||
},
|
||||
"include": [
|
||||
"src"
|
||||
]
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
SKIP_PREFLIGHT_CHECK=true
|
|
@ -21,3 +21,5 @@
|
|||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
|
||||
.eslintcache
|
||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -8,7 +8,7 @@
|
|||
"@testing-library/user-event": "^12.2.0",
|
||||
"react": "^17.0.1",
|
||||
"react-dom": "^17.0.1",
|
||||
"react-rest-request": "file:../../",
|
||||
"react-rest-request": "../../",
|
||||
"react-router-dom": "^5.2.0",
|
||||
"react-scripts": "4.0.0",
|
||||
"web-vitals": "^0.2.4"
|
||||
|
@ -40,6 +40,6 @@
|
|||
"devDependencies": {
|
||||
"@types/react-dom": "^16.9.9",
|
||||
"@types/react-router-dom": "^5.1.6",
|
||||
"typescript": "^4.0.5"
|
||||
"typescript": "4.0.5"
|
||||
}
|
||||
}
|
||||
|
|
|
@ -7,19 +7,25 @@ export type Movie = Readonly<{
|
|||
imdbId: string;
|
||||
}>
|
||||
|
||||
export const MoviesEndpoint: Endpoint = {
|
||||
export const MoviesEndpoint: Endpoint<MoviesResponse, void> = {
|
||||
method: Method.GET,
|
||||
url: '/action-adventure',
|
||||
transformResponseData(data: Movie[]) {
|
||||
return {
|
||||
items: data,
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export type MoviesResponse = Movie[];
|
||||
export type MoviesResponse = {
|
||||
items: Movie[],
|
||||
}
|
||||
|
||||
|
||||
export const MovieEndpoint: Endpoint<MovieParams> = {
|
||||
export const MovieEndpoint: Endpoint<MovieResponse, never, MovieParams> = {
|
||||
method: Method.GET,
|
||||
url: ({ id }) => `/action-adventure/${id}`,
|
||||
};
|
||||
|
||||
export type MovieParams = Readonly<{ id: React.Key }>;
|
||||
|
||||
export type MovieResponse = Movie[];
|
||||
export type MovieResponse = Movie;
|
||||
|
|
|
@ -1,17 +1,17 @@
|
|||
import React from 'react';
|
||||
import { useRequest } from 'react-rest-request';
|
||||
import { Link, useParams } from 'react-router-dom';
|
||||
import { MovieEndpoint, MovieParams, MovieResponse, MoviesEndpoint, MoviesResponse } from './endpoint';
|
||||
import { MovieEndpoint, MoviesEndpoint } from './endpoint';
|
||||
|
||||
|
||||
export function MoviesPage() {
|
||||
const { data, loading } = useRequest<MoviesResponse>(MoviesEndpoint);
|
||||
const { data, loading } = useRequest(MoviesEndpoint);
|
||||
|
||||
return !data ? (
|
||||
<div>{ loading ? 'Loading...' : 'Something went wrong' }</div>
|
||||
) : Array.isArray(data) ? (
|
||||
) : (
|
||||
<ul>
|
||||
{data
|
||||
{data.items
|
||||
.filter(movie => !!movie.title)
|
||||
.map(movie => (
|
||||
<li key={movie.id}>
|
||||
|
@ -22,12 +22,12 @@ export function MoviesPage() {
|
|||
<Link to='/9999'><span style={{color: 'red'}}>NOT EXIST</span></Link>
|
||||
</li>
|
||||
</ul>
|
||||
) : <div>{JSON.stringify(data)}</div>;
|
||||
);
|
||||
}
|
||||
|
||||
export function MoviePage() {
|
||||
const params = useParams<{ id: string}>();
|
||||
const { data, loading } = useRequest<MovieResponse, void, MovieParams>(
|
||||
const { data, loading } = useRequest(
|
||||
MovieEndpoint,
|
||||
{
|
||||
params,
|
||||
|
|
|
@ -1,24 +1,31 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
"target": "es5",
|
||||
"rootDir": "src",
|
||||
"outDir": "build",
|
||||
"module": "esnext",
|
||||
"target": "es6",
|
||||
"lib": [
|
||||
"dom",
|
||||
"dom.iterable",
|
||||
"esnext"
|
||||
"es2020"
|
||||
],
|
||||
"jsx": "react",
|
||||
"moduleResolution": "node",
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"esModuleInterop": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"strict": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "node",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"pretty": true,
|
||||
"noImplicitReturns": true,
|
||||
"noImplicitThis": true,
|
||||
"noImplicitAny": true,
|
||||
"noEmit": true,
|
||||
"jsx": "react"
|
||||
"strict": true,
|
||||
"strictNullChecks": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"declaration": true
|
||||
},
|
||||
"include": [
|
||||
"src"
|
||||
|
|
|
@ -0,0 +1,8 @@
|
|||
module.exports = {
|
||||
testRegex: 'tests/.*\\.spec\\.ts',
|
||||
testEnvironment: 'jsdom',
|
||||
preset: 'ts-jest',
|
||||
moduleFileExtensions: ['ts', 'js', 'json'],
|
||||
collectCoverage: true,
|
||||
collectCoverageFrom: ['src/**/*.ts', '!src/**/*.d.ts'],
|
||||
};
|
File diff suppressed because it is too large
Load Diff
22
package.json
22
package.json
|
@ -1,7 +1,7 @@
|
|||
{
|
||||
"name": "react-rest-request",
|
||||
"version": "0.3.0",
|
||||
"description": "Minimalistic REST API client for React inspired by Apollo",
|
||||
"version": "0.5.7",
|
||||
"description": "Minimalist REST API client for React inspired by Apollo",
|
||||
"readme": "README.md",
|
||||
"main": "./target/index.js",
|
||||
"types": "./target/index.d.ts",
|
||||
|
@ -9,7 +9,10 @@
|
|||
"target"
|
||||
],
|
||||
"scripts": {
|
||||
"prepublishOnly": "tsc"
|
||||
"test": "jest",
|
||||
"build": "tsc",
|
||||
"prepublishOnly": "rm -rf target && tsc",
|
||||
"report-coverage": "cat coverage/lcov.info | coveralls"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
@ -20,7 +23,9 @@
|
|||
"rest",
|
||||
"request",
|
||||
"fetch",
|
||||
"hook"
|
||||
"hook",
|
||||
"api",
|
||||
"client"
|
||||
],
|
||||
"author": "Dmitriy Pleshevskiy <dmitriy@ideascup.me>",
|
||||
"license": "MIT",
|
||||
|
@ -30,17 +35,24 @@
|
|||
"homepage": "https://github.com/pleshevskiy/react-rest-request#readme",
|
||||
"dependencies": {
|
||||
"lodash.isequal": "^4.5.0",
|
||||
"react": "^17.0.1",
|
||||
"tiny-invariant": "^1.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/jest": "^26.0.15",
|
||||
"@types/lodash.isequal": "^4.5.5",
|
||||
"@types/node-fetch": "^2.5.7",
|
||||
"@types/react": "^16.9.55",
|
||||
"@typescript-eslint/eslint-plugin": "^4.6.1",
|
||||
"@typescript-eslint/parser": "^4.6.1",
|
||||
"eslint": "^7.12.1",
|
||||
"eslint-plugin-react": "^7.21.5",
|
||||
"eslint-plugin-react-hooks": "^4.2.0",
|
||||
"jest": "^26.6.3",
|
||||
"node-fetch": "^2.6.1",
|
||||
"ts-jest": "^26.4.3",
|
||||
"typescript": "^4.0.5"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": "^16.3.0 || ^17.0.0"
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,7 +0,0 @@
|
|||
import { useRequestContext } from './request-context';
|
||||
|
||||
export function useClient() {
|
||||
const { client } = useRequestContext();
|
||||
|
||||
return [client];
|
||||
}
|
109
src/client.ts
109
src/client.ts
|
@ -1,32 +1,53 @@
|
|||
import invariant from 'tiny-invariant';
|
||||
import { Method } from './endpoint';
|
||||
import { formDataFromObject, urlSearchParamsFromObject } from './misc';
|
||||
import { Method, methodCanContainBody } from './endpoint';
|
||||
import { formDataFromObject, isFunction, urlSearchParamsFromObject } from './misc';
|
||||
|
||||
export type ClientConfig = {
|
||||
baseUrl: string,
|
||||
export interface ClientConfig {
|
||||
readonly baseUrl: string,
|
||||
}
|
||||
|
||||
export type RequestProps = {
|
||||
url: string,
|
||||
method: Method,
|
||||
headers: Record<string, string>,
|
||||
variables: Record<string, any> | FormData,
|
||||
export interface PrepareRequestProps {
|
||||
readonly url: string,
|
||||
readonly method: Method,
|
||||
readonly headers: Record<string, string>,
|
||||
readonly variables: Record<string, any> | FormData,
|
||||
}
|
||||
|
||||
export type ClientResponse<Data extends Record<string, any>> = Readonly<
|
||||
export interface RequestProps<R> extends PrepareRequestProps {
|
||||
readonly transformResponseData?: (data: unknown) => R,
|
||||
readonly abortSignal: AbortSignal,
|
||||
}
|
||||
|
||||
export interface ResponseWithError
|
||||
extends
|
||||
Pick<Response, 'ok' | 'redirected' | 'status' | 'statusText' | 'type' | 'headers' | 'url'>
|
||||
& { data: Data }
|
||||
>
|
||||
{
|
||||
readonly error?: Error,
|
||||
readonly canceled?: boolean,
|
||||
}
|
||||
|
||||
export interface ClientResponse<Data extends Record<string, any>>
|
||||
extends
|
||||
ResponseWithError
|
||||
{
|
||||
readonly data: Data
|
||||
}
|
||||
|
||||
export class Client {
|
||||
constructor(private config: ClientConfig) {}
|
||||
constructor(private readonly config: ClientConfig) {}
|
||||
|
||||
private prepareRequest(props: RequestProps) {
|
||||
const requestCanContainBody = [Method.POST, Method.PATCH, Method.PUT].includes(props.method);
|
||||
prepareRequest(props: PrepareRequestProps) {
|
||||
const requestCanContainBody = methodCanContainBody(props.method);
|
||||
|
||||
const url = /https?:\/\//.test(props.url) ?
|
||||
new URL(props.url)
|
||||
: new URL(this.config.baseUrl + props.url);
|
||||
const defaultBaseUrl = (window as Window | undefined)?.location.href;
|
||||
const sourceUrl = /https?:\/\//.test(props.url) ?
|
||||
props.url
|
||||
: this.config.baseUrl + props.url;
|
||||
if (!defaultBaseUrl && sourceUrl.startsWith('/')) {
|
||||
throw new Error(`Invalid request method: ${sourceUrl}`);
|
||||
}
|
||||
|
||||
const url = new URL(sourceUrl, defaultBaseUrl);
|
||||
if (!requestCanContainBody) {
|
||||
invariant(!(props.variables instanceof FormData), `Method ${props.method} cannot contain body`);
|
||||
|
||||
|
@ -54,20 +75,48 @@ export class Client {
|
|||
undefined
|
||||
);
|
||||
|
||||
return new Request(url.toString(), {
|
||||
headers,
|
||||
method: props.method,
|
||||
body,
|
||||
});
|
||||
return new Request(
|
||||
url.toString(),
|
||||
{
|
||||
headers,
|
||||
method: props.method,
|
||||
body,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
public request<Data extends Record<string, any>>(props: RequestProps): Promise<ClientResponse<Data>> {
|
||||
const req = this.prepareRequest(props);
|
||||
request<Data extends Record<string, any>>(
|
||||
{
|
||||
transformResponseData,
|
||||
abortSignal,
|
||||
...restProps
|
||||
}: RequestProps<Data>
|
||||
): Promise<ClientResponse<Data>> {
|
||||
const req = this.prepareRequest(restProps);
|
||||
|
||||
return fetch(req)
|
||||
return fetch(req, { signal: abortSignal })
|
||||
// TODO: need to check response headers and parse json only if content-type header is application/json
|
||||
.then(res => Promise.all([res, res.json(), false]))
|
||||
.then(([res, data]) => {
|
||||
.then(
|
||||
(res) => Promise.all([res, res.json()]),
|
||||
(err) => {
|
||||
const canceled = err.name === 'AbortError';
|
||||
return Promise.all([
|
||||
{
|
||||
ok: false,
|
||||
redirected: false,
|
||||
status: canceled ? 499 : 400,
|
||||
statusText: canceled ? 'Client Closed Request' : err.toString(),
|
||||
type: 'basic',
|
||||
headers: {},
|
||||
url: req.url,
|
||||
error: err,
|
||||
canceled,
|
||||
} as ResponseWithError,
|
||||
{}
|
||||
]);
|
||||
}
|
||||
)
|
||||
.then(([res, data]): ClientResponse<Data> => {
|
||||
return {
|
||||
ok: res.ok,
|
||||
redirected: res.redirected,
|
||||
|
@ -76,7 +125,9 @@ export class Client {
|
|||
type: res.type,
|
||||
headers: res.headers,
|
||||
url: res.url,
|
||||
data
|
||||
error: 'error' in res ? res.error : undefined,
|
||||
canceled: 'canceled' in res ? res.canceled : false,
|
||||
data: isFunction(transformResponseData) ? transformResponseData(data) : data,
|
||||
};
|
||||
})
|
||||
.then((res) => {
|
||||
|
|
|
@ -0,0 +1,7 @@
|
|||
import { useRequestContext } from './request_context';
|
||||
|
||||
export function useClient() {
|
||||
const { client } = useRequestContext();
|
||||
|
||||
return [client] as const;
|
||||
}
|
|
@ -1,5 +1,6 @@
|
|||
|
||||
export enum Method {
|
||||
HEAD = 'HEAD',
|
||||
GET = 'GET',
|
||||
PUT = 'PUT',
|
||||
POST = 'POST',
|
||||
|
@ -7,8 +8,24 @@ export enum Method {
|
|||
DELETE = 'DELETE',
|
||||
}
|
||||
|
||||
export type Endpoint<P = void> = Readonly<{
|
||||
export function methodCanContainBody(method: Method) {
|
||||
return [Method.POST, Method.PATCH, Method.PUT].includes(method);
|
||||
}
|
||||
|
||||
export function methodWithoutEffects(method: Method) {
|
||||
return [Method.HEAD, Method.GET].includes(method);
|
||||
}
|
||||
|
||||
export type Endpoint<R, V, P = unknown> = Readonly<{
|
||||
_?: V; // Temporary hack to extract the type of variables. Do not use it in real endpoints.
|
||||
method: Method;
|
||||
url: string | ((params: P) => string);
|
||||
headers?: Record<string, string>;
|
||||
}>
|
||||
transformResponseData?: (data: any) => R;
|
||||
}>
|
||||
|
||||
export type AnyEndpoint = Endpoint<any, any, any>
|
||||
|
||||
export type ExtractEndpointResponse<E> = E extends Endpoint<infer R, any, any> ? R : E extends Endpoint<infer R, any> ? R : never;
|
||||
export type ExtractEndpointVariables<E> = E extends Endpoint<any, infer V, any> ? V : E extends Endpoint<any, infer V> ? V : never;
|
||||
export type ExtractEndpointParams<E> = E extends Endpoint<any, any, infer P> ? P : never;
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
export * from './endpoint';
|
||||
export * from './client';
|
||||
export * from './client-hook';
|
||||
export * from './lazy-request-hook';
|
||||
export * from './request-hook';
|
||||
export * from './request-context';
|
||||
export * from './client_hook';
|
||||
export * from './lazy_request_hook';
|
||||
export * from './request_hook';
|
||||
export * from './request_context';
|
||||
export * from './reducer';
|
||||
|
|
|
@ -1,121 +0,0 @@
|
|||
import React from 'react';
|
||||
import invariant from 'tiny-invariant';
|
||||
import isEqual from 'lodash.isequal';
|
||||
import { useClient } from './client-hook';
|
||||
import { Endpoint } from './endpoint';
|
||||
import { PublicRequestState, RequestAction, requestReducer, RequestState } from './reducer';
|
||||
import { useRequestContext } from './request-context';
|
||||
import { ClientResponse } from './client';
|
||||
|
||||
export type LazyRequestConfig<R, V, P = void> = Readonly<{
|
||||
variables?: V;
|
||||
params?: P;
|
||||
headers?: Record<string, string>;
|
||||
onComplete?: (data: R) => unknown;
|
||||
onFailure?: (res: ClientResponse<R>) => unknown;
|
||||
}>
|
||||
|
||||
export type LazyRequestHandlerConfig<R, V, P> = Readonly<
|
||||
LazyRequestConfig<R, V, P>
|
||||
& { force?: boolean }
|
||||
>
|
||||
|
||||
export type RequestHandler<R, V, P> = (config?: LazyRequestHandlerConfig<R, V, P>) => Promise<R | null>;
|
||||
|
||||
export function useLazyRequest<R = Record<string, any>, V = Record<string, any>, P = void>(
|
||||
endpoint: Endpoint<P>,
|
||||
config?: LazyRequestConfig<R, V, P>,
|
||||
): [RequestHandler<R, V, P>, PublicRequestState<R>] {
|
||||
const [client] = useClient();
|
||||
const { defaultHeaders } = useRequestContext();
|
||||
const [state, dispatch] = React.useReducer<React.Reducer<RequestState<R>, RequestAction<R>>>(
|
||||
requestReducer,
|
||||
{
|
||||
data: null,
|
||||
loading: false,
|
||||
isCalled: false,
|
||||
}
|
||||
);
|
||||
|
||||
const handler = React.useCallback(
|
||||
(handlerConfig?: LazyRequestHandlerConfig<R, V, P>) => {
|
||||
if (state?.loading) {
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
|
||||
let params: P | undefined;
|
||||
let endpointUrl: string;
|
||||
let isSameRequest = true;
|
||||
if (typeof endpoint.url === 'function') {
|
||||
params = handlerConfig?.params ?? config?.params;
|
||||
invariant(params, 'Endpoind required params');
|
||||
|
||||
endpointUrl = endpoint.url(params);
|
||||
|
||||
isSameRequest = !!state?.prevParams && isEqual(state.prevParams, params);
|
||||
} else {
|
||||
endpointUrl = endpoint.url;
|
||||
}
|
||||
|
||||
const variables = {
|
||||
...config?.variables,
|
||||
...handlerConfig?.variables,
|
||||
};
|
||||
|
||||
const headers = {
|
||||
...defaultHeaders,
|
||||
...endpoint.headers,
|
||||
...config?.headers,
|
||||
...handlerConfig?.headers,
|
||||
};
|
||||
|
||||
if (
|
||||
isSameRequest
|
||||
&& state?.prevVariables && isEqual(state.prevVariables, variables)
|
||||
&& state?.prevHeaders && isEqual(state.prevHeaders, headers)
|
||||
&& !handlerConfig?.force
|
||||
) {
|
||||
return Promise.resolve(state.data);
|
||||
}
|
||||
|
||||
const onComplete = handlerConfig?.onComplete ?? config?.onComplete;
|
||||
const onFailure = handlerConfig?.onFailure ?? config?.onFailure;
|
||||
|
||||
dispatch({ type: 'call', headers, variables, params });
|
||||
|
||||
return client
|
||||
.request<R>({
|
||||
...endpoint,
|
||||
url: endpointUrl,
|
||||
headers,
|
||||
variables,
|
||||
})
|
||||
.then(
|
||||
(response) => {
|
||||
dispatch({ type: 'success', response });
|
||||
if (typeof onComplete === 'function') {
|
||||
onComplete(response.data);
|
||||
}
|
||||
return response.data;
|
||||
},
|
||||
(response) => {
|
||||
dispatch({ type: 'failure', response });
|
||||
if (typeof onFailure === 'function') {
|
||||
onFailure(response);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
);
|
||||
},
|
||||
[state, config, client, endpoint, defaultHeaders]
|
||||
);
|
||||
|
||||
return [
|
||||
handler,
|
||||
{
|
||||
data: state.data,
|
||||
loading: state.loading,
|
||||
isCalled: state.isCalled,
|
||||
},
|
||||
];
|
||||
}
|
|
@ -0,0 +1,187 @@
|
|||
import React from 'react';
|
||||
import invariant from 'tiny-invariant';
|
||||
import isEqual from 'lodash.isequal';
|
||||
import { useClient } from './client_hook';
|
||||
import { AnyEndpoint, ExtractEndpointParams, ExtractEndpointResponse, ExtractEndpointVariables, methodWithoutEffects } from './endpoint';
|
||||
import { INITIAL_REQUEST_STATE, PublicRequestState, RequestReducer, requestReducer } from './reducer';
|
||||
import { useRequestContext } from './request_context';
|
||||
import { ClientResponse } from './client';
|
||||
import { isFunction } from './misc';
|
||||
|
||||
export interface LazyRequestConfig<R, V, P> {
|
||||
readonly variables?: V;
|
||||
readonly params?: P;
|
||||
readonly headers?: Record<string, string>;
|
||||
readonly onComplete?: (data: R) => unknown;
|
||||
readonly onFailure?: (res: ClientResponse<R>) => unknown;
|
||||
}
|
||||
|
||||
export type LazyRequestConfigFromEndpoint<E extends AnyEndpoint> = LazyRequestConfig<
|
||||
ExtractEndpointResponse<E>,
|
||||
ExtractEndpointVariables<E>,
|
||||
ExtractEndpointParams<E>
|
||||
>;
|
||||
|
||||
export interface LazyRequestHandlerConfig<E extends AnyEndpoint>
|
||||
extends
|
||||
LazyRequestConfigFromEndpoint<E>
|
||||
{
|
||||
readonly force?: boolean
|
||||
}
|
||||
|
||||
export type RequestHandler<E extends AnyEndpoint> =
|
||||
(config?: LazyRequestHandlerConfig<E>) => Promise<ExtractEndpointResponse<E> | null>;
|
||||
|
||||
export interface PublicRequestStateWithActions<E extends AnyEndpoint>
|
||||
extends
|
||||
PublicRequestState<ExtractEndpointResponse<E>>
|
||||
{
|
||||
readonly refetch: () => void,
|
||||
readonly cancel: () => void,
|
||||
readonly clearStore: () => void,
|
||||
};
|
||||
|
||||
export function useLazyRequest<E extends AnyEndpoint>(
|
||||
endpoint: E,
|
||||
config?: LazyRequestConfigFromEndpoint<E>,
|
||||
): [RequestHandler<E>, PublicRequestStateWithActions<E>] {
|
||||
const [client] = useClient();
|
||||
const { defaultHeaders } = useRequestContext();
|
||||
const [state, dispatch] = React.useReducer<RequestReducer<ExtractEndpointResponse<E>>>(
|
||||
requestReducer,
|
||||
INITIAL_REQUEST_STATE,
|
||||
);
|
||||
const [prevHandlerConfig, setPrevHandlerConfig] = React.useState<LazyRequestHandlerConfig<E> | null>(null);
|
||||
|
||||
const abortControllerRef = React.useRef(new AbortController());
|
||||
|
||||
const transformResponseData = React.useCallback(
|
||||
(data: unknown): ExtractEndpointResponse<E> => {
|
||||
return isFunction(endpoint.transformResponseData) ?
|
||||
endpoint.transformResponseData(data)
|
||||
: data as ExtractEndpointResponse<E>;
|
||||
},
|
||||
[endpoint]
|
||||
);
|
||||
|
||||
const handler = React.useCallback(
|
||||
(handlerConfig?: LazyRequestHandlerConfig<E>) => {
|
||||
if (state?.loading || state?.isCanceled) {
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
|
||||
let params: ExtractEndpointParams<E> | undefined;
|
||||
let endpointUrl: string;
|
||||
let isSameRequest = true;
|
||||
if (isFunction(endpoint.url)) {
|
||||
params = handlerConfig?.params ?? config?.params;
|
||||
invariant(params, 'Endpoint required params');
|
||||
|
||||
endpointUrl = endpoint.url(params);
|
||||
|
||||
isSameRequest = !!state?.prevParams && isEqual(state.prevParams, params);
|
||||
} else {
|
||||
endpointUrl = endpoint.url;
|
||||
}
|
||||
|
||||
const variables = {
|
||||
...config?.variables,
|
||||
...handlerConfig?.variables,
|
||||
};
|
||||
|
||||
const headers = {
|
||||
...defaultHeaders,
|
||||
...endpoint.headers,
|
||||
...config?.headers,
|
||||
...handlerConfig?.headers,
|
||||
};
|
||||
|
||||
const shouldReturnCachedValue = (
|
||||
methodWithoutEffects(endpoint.method)
|
||||
&& state.isCalled
|
||||
&& isSameRequest
|
||||
&& state?.prevVariables && isEqual(state.prevVariables, variables)
|
||||
&& state?.prevHeaders && isEqual(state.prevHeaders, headers)
|
||||
&& !handlerConfig?.force
|
||||
);
|
||||
|
||||
if (shouldReturnCachedValue) {
|
||||
return Promise.resolve(state.data);
|
||||
}
|
||||
|
||||
const onCompletes = [config?.onComplete, handlerConfig?.onComplete].filter(isFunction);
|
||||
const onFailures = [config?.onFailure, handlerConfig?.onFailure].filter(isFunction);
|
||||
|
||||
dispatch({ type: 'call', headers, variables, params });
|
||||
|
||||
setPrevHandlerConfig(handlerConfig ?? {});
|
||||
|
||||
return client
|
||||
.request<ExtractEndpointResponse<E>>({
|
||||
...endpoint,
|
||||
abortSignal: abortControllerRef.current.signal,
|
||||
url: endpointUrl,
|
||||
headers,
|
||||
variables,
|
||||
transformResponseData,
|
||||
})
|
||||
.then(
|
||||
(response) => {
|
||||
dispatch({ type: 'success', response });
|
||||
|
||||
onCompletes.forEach(cb => cb(response.data));
|
||||
|
||||
return response.data;
|
||||
},
|
||||
(response: ClientResponse<ExtractEndpointResponse<E>>) => {
|
||||
dispatch({ type: 'failure', response });
|
||||
|
||||
if (!response.canceled) {
|
||||
onFailures.forEach(cb => cb(response));
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
);
|
||||
},
|
||||
[state, config, client, endpoint, defaultHeaders, transformResponseData]
|
||||
);
|
||||
|
||||
const refetchRequest = React.useCallback(
|
||||
() => {
|
||||
if (prevHandlerConfig != null) {
|
||||
handler({ ...prevHandlerConfig });
|
||||
}
|
||||
},
|
||||
[handler, prevHandlerConfig]
|
||||
);
|
||||
|
||||
const cancelRequest = React.useCallback(() => {
|
||||
dispatch({ type: 'cancel' });
|
||||
abortControllerRef.current.abort();
|
||||
abortControllerRef.current = new AbortController();
|
||||
}, []);
|
||||
|
||||
const clearRequestStore = React.useCallback(() => {
|
||||
dispatch({ type: 'clearStore' });
|
||||
}, []);
|
||||
|
||||
React.useEffect(
|
||||
() => cancelRequest,
|
||||
[cancelRequest]
|
||||
);
|
||||
|
||||
return [
|
||||
handler,
|
||||
{
|
||||
data: state.data,
|
||||
loading: state.loading,
|
||||
isCalled: state.isCalled,
|
||||
isCanceled: state.isCanceled,
|
||||
fetchError: state.fetchError,
|
||||
refetch: refetchRequest,
|
||||
cancel: cancelRequest,
|
||||
clearStore: clearRequestStore
|
||||
},
|
||||
];
|
||||
}
|
48
src/misc.ts
48
src/misc.ts
|
@ -1,33 +1,45 @@
|
|||
|
||||
export function isObject(val: any) {
|
||||
export function isObject(val: any): val is Record<string, unknown> {
|
||||
return Object.prototype.toString.call(val) === '[object Object]';
|
||||
}
|
||||
|
||||
export function isFunction(val: any): val is (...args: any[]) => any {
|
||||
return typeof val === 'function';
|
||||
}
|
||||
|
||||
export function formDataFromObject(obj: Record<string, any>) {
|
||||
const formData = new FormData();
|
||||
for (const [key, value] of Object.entries(obj)) {
|
||||
if (Array.isArray(value)) {
|
||||
value.forEach(val => formData.append(key, val));
|
||||
} else if (isObject(value)) {
|
||||
formData.set(key, JSON.stringify(value));
|
||||
} else {
|
||||
formData.set(key, value);
|
||||
}
|
||||
}
|
||||
Object.entries(obj)
|
||||
.filter(([_, value]) => value !== undefined)
|
||||
.forEach(([key, value]) => {
|
||||
if (Array.isArray(value)) {
|
||||
value
|
||||
.filter(val => val !== undefined)
|
||||
.forEach(val => formData.append(key, val));
|
||||
} else if (isObject(value)) {
|
||||
formData.set(key, JSON.stringify(value));
|
||||
} else {
|
||||
formData.set(key, value);
|
||||
}
|
||||
});
|
||||
|
||||
return formData;
|
||||
}
|
||||
|
||||
export function urlSearchParamsFromObject(obj: Record<string, any>) {
|
||||
const searchParams = new URLSearchParams();
|
||||
for (const [key, value] of Object.entries(obj)) {
|
||||
if (Array.isArray(value)) {
|
||||
const arrayKey = `${key}[]`;
|
||||
value.forEach(val => searchParams.append(arrayKey, val));
|
||||
} else {
|
||||
searchParams.set(key, value);
|
||||
}
|
||||
}
|
||||
Object.entries(obj)
|
||||
.filter(([_, value]) => value !== undefined)
|
||||
.forEach(([key, value]) => {
|
||||
if (Array.isArray(value)) {
|
||||
const arrayKey = `${key}[]`;
|
||||
value
|
||||
.filter(val => val !== undefined)
|
||||
.forEach(val => searchParams.append(arrayKey, val));
|
||||
} else {
|
||||
searchParams.set(key, value);
|
||||
}
|
||||
});
|
||||
|
||||
return searchParams;
|
||||
}
|
||||
|
|
|
@ -1,26 +1,64 @@
|
|||
import { ClientResponse } from './client';
|
||||
|
||||
export type RequestState<R> = Readonly<{
|
||||
data: R | null;
|
||||
loading: boolean;
|
||||
isCalled: boolean;
|
||||
prevHeaders?: Record<string, string>;
|
||||
prevVariables?: Record<string, any>;
|
||||
prevParams?: Record<string, any>
|
||||
}>
|
||||
export interface PublicRequestState<R> {
|
||||
readonly data: R | null;
|
||||
readonly loading: boolean;
|
||||
readonly isCalled: boolean;
|
||||
readonly isCanceled?: boolean;
|
||||
readonly response?: ClientResponse<R>;
|
||||
readonly fetchError?: Error;
|
||||
}
|
||||
|
||||
export type PublicRequestState<R> = Pick<RequestState<R>, 'data' | 'loading' | 'isCalled'>;
|
||||
export interface RequestState<R> extends PublicRequestState<R> {
|
||||
readonly prevHeaders?: Record<string, string>;
|
||||
readonly prevVariables?: Record<string, any>;
|
||||
readonly prevParams?: Record<string, any>;
|
||||
}
|
||||
|
||||
export type RequestAction<R> =
|
||||
| { type: 'call', headers: Record<string, string>, variables: Record<string, any>, params?: Record<string, any> }
|
||||
| { type: 'success', response: ClientResponse<R> }
|
||||
| { type: 'failure', response: ClientResponse<R> }
|
||||
| {
|
||||
type: 'call',
|
||||
headers: Record<string, string>,
|
||||
variables: Record<string, any>,
|
||||
params?: Record<string, any>
|
||||
}
|
||||
| {
|
||||
type: 'success',
|
||||
response: ClientResponse<R>
|
||||
}
|
||||
| {
|
||||
type: 'failure',
|
||||
response: ClientResponse<R>
|
||||
}
|
||||
| {
|
||||
type: 'cancel'
|
||||
}
|
||||
| {
|
||||
type: 'clearStore'
|
||||
}
|
||||
|
||||
export function requestReducer<R>(state: RequestState<R>, action: RequestAction<R>) {
|
||||
export type RequestReducer<R> = React.Reducer<RequestState<R>, RequestAction<R>>
|
||||
|
||||
export const INITIAL_REQUEST_STATE: RequestState<any> = {
|
||||
data: null,
|
||||
response: undefined,
|
||||
fetchError: undefined,
|
||||
isCanceled: false,
|
||||
loading: false,
|
||||
isCalled: false,
|
||||
prevHeaders: undefined,
|
||||
prevVariables: undefined,
|
||||
prevParams: undefined,
|
||||
};
|
||||
|
||||
export function requestReducer<R>(state: RequestState<R>, action: RequestAction<R>): RequestState<R> {
|
||||
switch (action.type) {
|
||||
case 'call': {
|
||||
return {
|
||||
...state,
|
||||
response: undefined,
|
||||
fetchError: undefined,
|
||||
isCanceled: false,
|
||||
loading: true,
|
||||
isCalled: true,
|
||||
prevHeaders: action.headers,
|
||||
|
@ -32,6 +70,7 @@ export function requestReducer<R>(state: RequestState<R>, action: RequestAction<
|
|||
return {
|
||||
...state,
|
||||
loading: false,
|
||||
response: action.response,
|
||||
data: action.response.data,
|
||||
};
|
||||
}
|
||||
|
@ -39,9 +78,22 @@ export function requestReducer<R>(state: RequestState<R>, action: RequestAction<
|
|||
return {
|
||||
...state,
|
||||
loading: false,
|
||||
response: action.response,
|
||||
data: null,
|
||||
// TODO: need to append errors
|
||||
fetchError: action.response.error,
|
||||
isCanceled: action.response.canceled,
|
||||
};
|
||||
}
|
||||
case 'cancel': {
|
||||
return {
|
||||
...state,
|
||||
isCanceled: true,
|
||||
fetchError: undefined,
|
||||
};
|
||||
}
|
||||
case 'clearStore': {
|
||||
return INITIAL_REQUEST_STATE;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -3,10 +3,10 @@ import invariant from 'tiny-invariant';
|
|||
import { Client } from './client';
|
||||
|
||||
|
||||
export type RequestContextData = Readonly<{
|
||||
client: Client;
|
||||
defaultHeaders?: Record<string, string>;
|
||||
}>
|
||||
export interface RequestContextData {
|
||||
readonly client: Client;
|
||||
readonly defaultHeaders?: Record<string, string>;
|
||||
}
|
||||
|
||||
const RequestContext = React.createContext<RequestContextData | null>(null);
|
||||
|
|
@ -1,21 +1,21 @@
|
|||
import React from 'react';
|
||||
import invariant from 'tiny-invariant';
|
||||
import { Endpoint, Method } from './endpoint';
|
||||
import { LazyRequestConfig, useLazyRequest } from './lazy-request-hook';
|
||||
import { AnyEndpoint, methodWithoutEffects } from './endpoint';
|
||||
import { LazyRequestConfigFromEndpoint, useLazyRequest } from './lazy_request_hook';
|
||||
|
||||
export type RequestConfig<R, V, P> = Readonly<
|
||||
LazyRequestConfig<R, V, P>
|
||||
& {
|
||||
skip?: boolean,
|
||||
}
|
||||
>
|
||||
export interface RequestConfigFromEndpoint<E extends AnyEndpoint>
|
||||
extends
|
||||
LazyRequestConfigFromEndpoint<E>
|
||||
{
|
||||
readonly skip?: boolean,
|
||||
}
|
||||
|
||||
export function useRequest<R = Record<string, any>, V = Record<string, any>, P = void>(
|
||||
endpoint: Endpoint<P>,
|
||||
config?: RequestConfig<R, V, P>,
|
||||
export function useRequest<E extends AnyEndpoint>(
|
||||
endpoint: E,
|
||||
config?: RequestConfigFromEndpoint<E>,
|
||||
) {
|
||||
invariant(
|
||||
endpoint.method == Method.GET,
|
||||
methodWithoutEffects(endpoint.method),
|
||||
`You cannot use useRequest with ${endpoint.method} method`
|
||||
);
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
import { Method } from './endpoint';
|
||||
export interface ClientConfig {
|
||||
readonly baseUrl: string;
|
||||
}
|
||||
export interface PrepareRequestProps {
|
||||
readonly url: string;
|
||||
readonly method: Method;
|
||||
readonly headers: Record<string, string>;
|
||||
readonly variables: Record<string, any> | FormData;
|
||||
}
|
||||
export interface RequestProps<R> extends PrepareRequestProps {
|
||||
readonly transformResponseData?: (data: unknown) => R;
|
||||
readonly abortSignal: AbortSignal;
|
||||
}
|
||||
export interface ResponseWithError extends Pick<Response, 'ok' | 'redirected' | 'status' | 'statusText' | 'type' | 'headers' | 'url'> {
|
||||
readonly error?: Error;
|
||||
readonly canceled?: boolean;
|
||||
}
|
||||
export interface ClientResponse<Data extends Record<string, any>> extends ResponseWithError {
|
||||
readonly data: Data;
|
||||
}
|
||||
export declare class Client {
|
||||
private readonly config;
|
||||
constructor(config: ClientConfig);
|
||||
prepareRequest(props: PrepareRequestProps): Request;
|
||||
request<Data extends Record<string, any>>({ transformResponseData, abortSignal, ...restProps }: RequestProps<Data>): Promise<ClientResponse<Data>>;
|
||||
}
|
|
@ -0,0 +1,95 @@
|
|||
"use strict";
|
||||
var __rest = (this && this.__rest) || function (s, e) {
|
||||
var t = {};
|
||||
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
|
||||
t[p] = s[p];
|
||||
if (s != null && typeof Object.getOwnPropertySymbols === "function")
|
||||
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
|
||||
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
|
||||
t[p[i]] = s[p[i]];
|
||||
}
|
||||
return t;
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.Client = void 0;
|
||||
const tiny_invariant_1 = require("tiny-invariant");
|
||||
const endpoint_1 = require("./endpoint");
|
||||
const misc_1 = require("./misc");
|
||||
class Client {
|
||||
constructor(config) {
|
||||
this.config = config;
|
||||
}
|
||||
prepareRequest(props) {
|
||||
var _a;
|
||||
const requestCanContainBody = endpoint_1.methodCanContainBody(props.method);
|
||||
const defaultBaseUrl = (_a = window) === null || _a === void 0 ? void 0 : _a.location.href;
|
||||
const sourceUrl = /https?:\/\//.test(props.url) ?
|
||||
props.url
|
||||
: this.config.baseUrl + props.url;
|
||||
if (!defaultBaseUrl && sourceUrl.startsWith('/')) {
|
||||
throw new Error(`Invalid request method: ${sourceUrl}`);
|
||||
}
|
||||
const url = new URL(sourceUrl, defaultBaseUrl);
|
||||
if (!requestCanContainBody) {
|
||||
tiny_invariant_1.default(!(props.variables instanceof FormData), `Method ${props.method} cannot contain body`);
|
||||
url.search = misc_1.urlSearchParamsFromObject(props.variables).toString();
|
||||
}
|
||||
const headers = new Headers(props.headers);
|
||||
if (requestCanContainBody && !headers.has('content-type')) {
|
||||
headers.set('content-type', 'application/json');
|
||||
}
|
||||
const contentType = headers.get('content-type');
|
||||
const body = !requestCanContainBody ? (undefined) : contentType === 'application/json' ? (JSON.stringify(props.variables)) : contentType === 'multipart/form-data' ? (props.variables instanceof FormData ? (props.variables) : (misc_1.formDataFromObject(props.variables))) : (
|
||||
/* TODO: need to add more content-type of body */
|
||||
undefined);
|
||||
return new Request(url.toString(), {
|
||||
headers,
|
||||
method: props.method,
|
||||
body,
|
||||
});
|
||||
}
|
||||
request(_a) {
|
||||
var { transformResponseData, abortSignal } = _a, restProps = __rest(_a, ["transformResponseData", "abortSignal"]);
|
||||
const req = this.prepareRequest(restProps);
|
||||
return fetch(req, { signal: abortSignal })
|
||||
// TODO: need to check response headers and parse json only if content-type header is application/json
|
||||
.then((res) => Promise.all([res, res.json()]), (err) => {
|
||||
const canceled = err.name === 'AbortError';
|
||||
return Promise.all([
|
||||
{
|
||||
ok: false,
|
||||
redirected: false,
|
||||
status: canceled ? 499 : 400,
|
||||
statusText: canceled ? 'Client Closed Request' : err.toString(),
|
||||
type: 'basic',
|
||||
headers: {},
|
||||
url: req.url,
|
||||
error: err,
|
||||
canceled,
|
||||
},
|
||||
{}
|
||||
]);
|
||||
})
|
||||
.then(([res, data]) => {
|
||||
return {
|
||||
ok: res.ok,
|
||||
redirected: res.redirected,
|
||||
status: res.status,
|
||||
statusText: res.statusText,
|
||||
type: res.type,
|
||||
headers: res.headers,
|
||||
url: res.url,
|
||||
error: 'error' in res ? res.error : undefined,
|
||||
canceled: 'canceled' in res ? res.canceled : false,
|
||||
data: misc_1.isFunction(transformResponseData) ? transformResponseData(data) : data,
|
||||
};
|
||||
})
|
||||
.then((res) => {
|
||||
if (!res.ok) {
|
||||
throw res;
|
||||
}
|
||||
return res;
|
||||
});
|
||||
}
|
||||
}
|
||||
exports.Client = Client;
|
|
@ -0,0 +1 @@
|
|||
export declare function useClient(): readonly [import("./client").Client];
|
|
@ -0,0 +1,9 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.useClient = void 0;
|
||||
const request_context_1 = require("./request_context");
|
||||
function useClient() {
|
||||
const { client } = request_context_1.useRequestContext();
|
||||
return [client];
|
||||
}
|
||||
exports.useClient = useClient;
|
|
@ -0,0 +1,21 @@
|
|||
export declare enum Method {
|
||||
HEAD = "HEAD",
|
||||
GET = "GET",
|
||||
PUT = "PUT",
|
||||
POST = "POST",
|
||||
PATCH = "PATCH",
|
||||
DELETE = "DELETE"
|
||||
}
|
||||
export declare function methodCanContainBody(method: Method): boolean;
|
||||
export declare function methodWithoutEffects(method: Method): boolean;
|
||||
export declare type Endpoint<R, V, P = unknown> = Readonly<{
|
||||
_?: V;
|
||||
method: Method;
|
||||
url: string | ((params: P) => string);
|
||||
headers?: Record<string, string>;
|
||||
transformResponseData?: (data: any) => R;
|
||||
}>;
|
||||
export declare type AnyEndpoint = Endpoint<any, any, any>;
|
||||
export declare type ExtractEndpointResponse<E> = E extends Endpoint<infer R, any, any> ? R : E extends Endpoint<infer R, any> ? R : never;
|
||||
export declare type ExtractEndpointVariables<E> = E extends Endpoint<any, infer V, any> ? V : E extends Endpoint<any, infer V> ? V : never;
|
||||
export declare type ExtractEndpointParams<E> = E extends Endpoint<any, any, infer P> ? P : never;
|
|
@ -0,0 +1,20 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.methodWithoutEffects = exports.methodCanContainBody = exports.Method = void 0;
|
||||
var Method;
|
||||
(function (Method) {
|
||||
Method["HEAD"] = "HEAD";
|
||||
Method["GET"] = "GET";
|
||||
Method["PUT"] = "PUT";
|
||||
Method["POST"] = "POST";
|
||||
Method["PATCH"] = "PATCH";
|
||||
Method["DELETE"] = "DELETE";
|
||||
})(Method = exports.Method || (exports.Method = {}));
|
||||
function methodCanContainBody(method) {
|
||||
return [Method.POST, Method.PATCH, Method.PUT].includes(method);
|
||||
}
|
||||
exports.methodCanContainBody = methodCanContainBody;
|
||||
function methodWithoutEffects(method) {
|
||||
return [Method.HEAD, Method.GET].includes(method);
|
||||
}
|
||||
exports.methodWithoutEffects = methodWithoutEffects;
|
|
@ -0,0 +1,7 @@
|
|||
export * from './endpoint';
|
||||
export * from './client';
|
||||
export * from './client_hook';
|
||||
export * from './lazy_request_hook';
|
||||
export * from './request_hook';
|
||||
export * from './request_context';
|
||||
export * from './reducer';
|
|
@ -0,0 +1,19 @@
|
|||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
||||
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
__exportStar(require("./endpoint"), exports);
|
||||
__exportStar(require("./client"), exports);
|
||||
__exportStar(require("./client_hook"), exports);
|
||||
__exportStar(require("./lazy_request_hook"), exports);
|
||||
__exportStar(require("./request_hook"), exports);
|
||||
__exportStar(require("./request_context"), exports);
|
||||
__exportStar(require("./reducer"), exports);
|
|
@ -0,0 +1,21 @@
|
|||
import { AnyEndpoint, ExtractEndpointParams, ExtractEndpointResponse, ExtractEndpointVariables } from './endpoint';
|
||||
import { PublicRequestState } from './reducer';
|
||||
import { ClientResponse } from './client';
|
||||
export interface LazyRequestConfig<R, V, P> {
|
||||
readonly variables?: V;
|
||||
readonly params?: P;
|
||||
readonly headers?: Record<string, string>;
|
||||
readonly onComplete?: (data: R) => unknown;
|
||||
readonly onFailure?: (res: ClientResponse<R>) => unknown;
|
||||
}
|
||||
export declare type LazyRequestConfigFromEndpoint<E extends AnyEndpoint> = LazyRequestConfig<ExtractEndpointResponse<E>, ExtractEndpointVariables<E>, ExtractEndpointParams<E>>;
|
||||
export interface LazyRequestHandlerConfig<E extends AnyEndpoint> extends LazyRequestConfigFromEndpoint<E> {
|
||||
readonly force?: boolean;
|
||||
}
|
||||
export declare type RequestHandler<E extends AnyEndpoint> = (config?: LazyRequestHandlerConfig<E>) => Promise<ExtractEndpointResponse<E> | null>;
|
||||
export interface PublicRequestStateWithActions<E extends AnyEndpoint> extends PublicRequestState<ExtractEndpointResponse<E>> {
|
||||
readonly refetch: () => void;
|
||||
readonly cancel: () => void;
|
||||
readonly clearStore: () => void;
|
||||
}
|
||||
export declare function useLazyRequest<E extends AnyEndpoint>(endpoint: E, config?: LazyRequestConfigFromEndpoint<E>): [RequestHandler<E>, PublicRequestStateWithActions<E>];
|
|
@ -0,0 +1,100 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.useLazyRequest = void 0;
|
||||
const react_1 = require("react");
|
||||
const tiny_invariant_1 = require("tiny-invariant");
|
||||
const lodash_isequal_1 = require("lodash.isequal");
|
||||
const client_hook_1 = require("./client_hook");
|
||||
const endpoint_1 = require("./endpoint");
|
||||
const reducer_1 = require("./reducer");
|
||||
const request_context_1 = require("./request_context");
|
||||
const misc_1 = require("./misc");
|
||||
;
|
||||
function useLazyRequest(endpoint, config) {
|
||||
const [client] = client_hook_1.useClient();
|
||||
const { defaultHeaders } = request_context_1.useRequestContext();
|
||||
const [state, dispatch] = react_1.default.useReducer(reducer_1.requestReducer, reducer_1.INITIAL_REQUEST_STATE);
|
||||
const [prevHandlerConfig, setPrevHandlerConfig] = react_1.default.useState(null);
|
||||
const abortControllerRef = react_1.default.useRef(new AbortController());
|
||||
const transformResponseData = react_1.default.useCallback((data) => {
|
||||
return misc_1.isFunction(endpoint.transformResponseData) ?
|
||||
endpoint.transformResponseData(data)
|
||||
: data;
|
||||
}, [endpoint]);
|
||||
const handler = react_1.default.useCallback((handlerConfig) => {
|
||||
var _a;
|
||||
if ((state === null || state === void 0 ? void 0 : state.loading) || (state === null || state === void 0 ? void 0 : state.isCanceled)) {
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
let params;
|
||||
let endpointUrl;
|
||||
let isSameRequest = true;
|
||||
if (misc_1.isFunction(endpoint.url)) {
|
||||
params = (_a = handlerConfig === null || handlerConfig === void 0 ? void 0 : handlerConfig.params) !== null && _a !== void 0 ? _a : config === null || config === void 0 ? void 0 : config.params;
|
||||
tiny_invariant_1.default(params, 'Endpoint required params');
|
||||
endpointUrl = endpoint.url(params);
|
||||
isSameRequest = !!(state === null || state === void 0 ? void 0 : state.prevParams) && lodash_isequal_1.default(state.prevParams, params);
|
||||
}
|
||||
else {
|
||||
endpointUrl = endpoint.url;
|
||||
}
|
||||
const variables = Object.assign(Object.assign({}, config === null || config === void 0 ? void 0 : config.variables), handlerConfig === null || handlerConfig === void 0 ? void 0 : handlerConfig.variables);
|
||||
const headers = Object.assign(Object.assign(Object.assign(Object.assign({}, defaultHeaders), endpoint.headers), config === null || config === void 0 ? void 0 : config.headers), handlerConfig === null || handlerConfig === void 0 ? void 0 : handlerConfig.headers);
|
||||
const shouldReturnCachedValue = (endpoint_1.methodWithoutEffects(endpoint.method)
|
||||
&& state.isCalled
|
||||
&& isSameRequest
|
||||
&& (state === null || state === void 0 ? void 0 : state.prevVariables) && lodash_isequal_1.default(state.prevVariables, variables)
|
||||
&& (state === null || state === void 0 ? void 0 : state.prevHeaders) && lodash_isequal_1.default(state.prevHeaders, headers)
|
||||
&& !(handlerConfig === null || handlerConfig === void 0 ? void 0 : handlerConfig.force));
|
||||
if (shouldReturnCachedValue) {
|
||||
return Promise.resolve(state.data);
|
||||
}
|
||||
const onCompletes = [config === null || config === void 0 ? void 0 : config.onComplete, handlerConfig === null || handlerConfig === void 0 ? void 0 : handlerConfig.onComplete].filter(misc_1.isFunction);
|
||||
const onFailures = [config === null || config === void 0 ? void 0 : config.onFailure, handlerConfig === null || handlerConfig === void 0 ? void 0 : handlerConfig.onFailure].filter(misc_1.isFunction);
|
||||
dispatch({ type: 'call', headers, variables, params });
|
||||
setPrevHandlerConfig(handlerConfig !== null && handlerConfig !== void 0 ? handlerConfig : {});
|
||||
return client
|
||||
.request(Object.assign(Object.assign({}, endpoint), { abortSignal: abortControllerRef.current.signal, url: endpointUrl, headers,
|
||||
variables,
|
||||
transformResponseData }))
|
||||
.then((response) => {
|
||||
dispatch({ type: 'success', response });
|
||||
onCompletes.forEach(cb => cb(response.data));
|
||||
return response.data;
|
||||
}, (response) => {
|
||||
dispatch({ type: 'failure', response });
|
||||
if (!response.canceled) {
|
||||
onFailures.forEach(cb => cb(response));
|
||||
}
|
||||
return null;
|
||||
});
|
||||
}, [state, config, client, endpoint, defaultHeaders, transformResponseData]);
|
||||
const refetchRequest = react_1.default.useCallback(() => {
|
||||
if (prevHandlerConfig != null) {
|
||||
handler(Object.assign({}, prevHandlerConfig));
|
||||
}
|
||||
}, [handler, prevHandlerConfig]);
|
||||
const cancelRequest = react_1.default.useCallback(() => {
|
||||
dispatch({ type: 'cancel' });
|
||||
abortControllerRef.current.abort();
|
||||
abortControllerRef.current = new AbortController();
|
||||
}, []);
|
||||
const clearRequestStore = react_1.default.useCallback(() => {
|
||||
dispatch({ type: 'clearStore' });
|
||||
}, []);
|
||||
react_1.default.useEffect(() => cancelRequest, [cancelRequest]);
|
||||
return [
|
||||
handler,
|
||||
{
|
||||
data: state.data,
|
||||
loading: state.loading,
|
||||
isCalled: state.isCalled,
|
||||
isCanceled: state.isCanceled,
|
||||
fetchError: state.fetchError,
|
||||
refetch: refetchRequest,
|
||||
cancel: cancelRequest,
|
||||
clearStore: clearRequestStore
|
||||
},
|
||||
];
|
||||
}
|
||||
exports.useLazyRequest = useLazyRequest;
|
|
@ -0,0 +1,4 @@
|
|||
export declare function isObject(val: any): val is Record<string, unknown>;
|
||||
export declare function isFunction(val: any): val is (...args: any[]) => any;
|
||||
export declare function formDataFromObject(obj: Record<string, any>): FormData;
|
||||
export declare function urlSearchParamsFromObject(obj: Record<string, any>): URLSearchParams;
|
|
@ -0,0 +1,49 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.urlSearchParamsFromObject = exports.formDataFromObject = exports.isFunction = exports.isObject = void 0;
|
||||
function isObject(val) {
|
||||
return Object.prototype.toString.call(val) === '[object Object]';
|
||||
}
|
||||
exports.isObject = isObject;
|
||||
function isFunction(val) {
|
||||
return typeof val === 'function';
|
||||
}
|
||||
exports.isFunction = isFunction;
|
||||
function formDataFromObject(obj) {
|
||||
const formData = new FormData();
|
||||
Object.entries(obj)
|
||||
.filter(([_, value]) => value !== undefined)
|
||||
.forEach(([key, value]) => {
|
||||
if (Array.isArray(value)) {
|
||||
value
|
||||
.filter(val => val !== undefined)
|
||||
.forEach(val => formData.append(key, val));
|
||||
}
|
||||
else if (isObject(value)) {
|
||||
formData.set(key, JSON.stringify(value));
|
||||
}
|
||||
else {
|
||||
formData.set(key, value);
|
||||
}
|
||||
});
|
||||
return formData;
|
||||
}
|
||||
exports.formDataFromObject = formDataFromObject;
|
||||
function urlSearchParamsFromObject(obj) {
|
||||
const searchParams = new URLSearchParams();
|
||||
Object.entries(obj)
|
||||
.filter(([_, value]) => value !== undefined)
|
||||
.forEach(([key, value]) => {
|
||||
if (Array.isArray(value)) {
|
||||
const arrayKey = `${key}[]`;
|
||||
value
|
||||
.filter(val => val !== undefined)
|
||||
.forEach(val => searchParams.append(arrayKey, val));
|
||||
}
|
||||
else {
|
||||
searchParams.set(key, value);
|
||||
}
|
||||
});
|
||||
return searchParams;
|
||||
}
|
||||
exports.urlSearchParamsFromObject = urlSearchParamsFromObject;
|
|
@ -0,0 +1,34 @@
|
|||
/// <reference types="react" />
|
||||
import { ClientResponse } from './client';
|
||||
export interface PublicRequestState<R> {
|
||||
readonly data: R | null;
|
||||
readonly loading: boolean;
|
||||
readonly isCalled: boolean;
|
||||
readonly isCanceled?: boolean;
|
||||
readonly response?: ClientResponse<R>;
|
||||
readonly fetchError?: Error;
|
||||
}
|
||||
export interface RequestState<R> extends PublicRequestState<R> {
|
||||
readonly prevHeaders?: Record<string, string>;
|
||||
readonly prevVariables?: Record<string, any>;
|
||||
readonly prevParams?: Record<string, any>;
|
||||
}
|
||||
export declare type RequestAction<R> = {
|
||||
type: 'call';
|
||||
headers: Record<string, string>;
|
||||
variables: Record<string, any>;
|
||||
params?: Record<string, any>;
|
||||
} | {
|
||||
type: 'success';
|
||||
response: ClientResponse<R>;
|
||||
} | {
|
||||
type: 'failure';
|
||||
response: ClientResponse<R>;
|
||||
} | {
|
||||
type: 'cancel';
|
||||
} | {
|
||||
type: 'clearStore';
|
||||
};
|
||||
export declare type RequestReducer<R> = React.Reducer<RequestState<R>, RequestAction<R>>;
|
||||
export declare const INITIAL_REQUEST_STATE: RequestState<any>;
|
||||
export declare function requestReducer<R>(state: RequestState<R>, action: RequestAction<R>): RequestState<R>;
|
|
@ -0,0 +1,34 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.requestReducer = exports.INITIAL_REQUEST_STATE = void 0;
|
||||
exports.INITIAL_REQUEST_STATE = {
|
||||
data: null,
|
||||
response: undefined,
|
||||
fetchError: undefined,
|
||||
isCanceled: false,
|
||||
loading: false,
|
||||
isCalled: false,
|
||||
prevHeaders: undefined,
|
||||
prevVariables: undefined,
|
||||
prevParams: undefined,
|
||||
};
|
||||
function requestReducer(state, action) {
|
||||
switch (action.type) {
|
||||
case 'call': {
|
||||
return Object.assign(Object.assign({}, state), { response: undefined, fetchError: undefined, isCanceled: false, loading: true, isCalled: true, prevHeaders: action.headers, prevVariables: action.variables, prevParams: action.params });
|
||||
}
|
||||
case 'success': {
|
||||
return Object.assign(Object.assign({}, state), { loading: false, response: action.response, data: action.response.data });
|
||||
}
|
||||
case 'failure': {
|
||||
return Object.assign(Object.assign({}, state), { loading: false, response: action.response, data: null, fetchError: action.response.error, isCanceled: action.response.canceled });
|
||||
}
|
||||
case 'cancel': {
|
||||
return Object.assign(Object.assign({}, state), { isCanceled: true, fetchError: undefined });
|
||||
}
|
||||
case 'clearStore': {
|
||||
return exports.INITIAL_REQUEST_STATE;
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.requestReducer = requestReducer;
|
|
@ -0,0 +1,9 @@
|
|||
import React from 'react';
|
||||
import { Client } from './client';
|
||||
export interface RequestContextData {
|
||||
readonly client: Client;
|
||||
readonly defaultHeaders?: Record<string, string>;
|
||||
}
|
||||
export declare type RequestProviderProps = Readonly<React.PropsWithChildren<RequestContextData>>;
|
||||
export declare function RequestProvider({ client, defaultHeaders, children }: RequestProviderProps): JSX.Element;
|
||||
export declare function useRequestContext(): RequestContextData;
|
|
@ -0,0 +1,16 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.useRequestContext = exports.RequestProvider = void 0;
|
||||
const react_1 = require("react");
|
||||
const tiny_invariant_1 = require("tiny-invariant");
|
||||
const RequestContext = react_1.default.createContext(null);
|
||||
function RequestProvider({ client, defaultHeaders, children }) {
|
||||
return (react_1.default.createElement(RequestContext.Provider, { value: { client, defaultHeaders } }, children));
|
||||
}
|
||||
exports.RequestProvider = RequestProvider;
|
||||
function useRequestContext() {
|
||||
const context = react_1.default.useContext(RequestContext);
|
||||
tiny_invariant_1.default(context, 'useRequestContext() must be a child of <RequestProvider />');
|
||||
return context;
|
||||
}
|
||||
exports.useRequestContext = useRequestContext;
|
|
@ -0,0 +1,6 @@
|
|||
import { AnyEndpoint } from './endpoint';
|
||||
import { LazyRequestConfigFromEndpoint } from './lazy_request_hook';
|
||||
export interface RequestConfigFromEndpoint<E extends AnyEndpoint> extends LazyRequestConfigFromEndpoint<E> {
|
||||
readonly skip?: boolean;
|
||||
}
|
||||
export declare function useRequest<E extends AnyEndpoint>(endpoint: E, config?: RequestConfigFromEndpoint<E>): import("./lazy_request_hook").PublicRequestStateWithActions<E>;
|
|
@ -0,0 +1,19 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.useRequest = void 0;
|
||||
const react_1 = require("react");
|
||||
const tiny_invariant_1 = require("tiny-invariant");
|
||||
const endpoint_1 = require("./endpoint");
|
||||
const lazy_request_hook_1 = require("./lazy_request_hook");
|
||||
function useRequest(endpoint, config) {
|
||||
tiny_invariant_1.default(endpoint_1.methodWithoutEffects(endpoint.method), `You cannot use useRequest with ${endpoint.method} method`);
|
||||
const [handler, state] = lazy_request_hook_1.useLazyRequest(endpoint, config);
|
||||
const skip = react_1.default.useMemo(() => { var _a; return (_a = config === null || config === void 0 ? void 0 : config.skip) !== null && _a !== void 0 ? _a : false; }, [config]);
|
||||
react_1.default.useEffect(() => {
|
||||
if (!skip) {
|
||||
handler();
|
||||
}
|
||||
}, [skip, handler]);
|
||||
return state;
|
||||
}
|
||||
exports.useRequest = useRequest;
|
|
@ -0,0 +1,46 @@
|
|||
import { Client } from '../src/client';
|
||||
import { Method } from '../src/endpoint';
|
||||
import * as nodeFetch from 'node-fetch';
|
||||
|
||||
beforeAll(() => {
|
||||
global.Response = nodeFetch.Response as any;
|
||||
global.Request = nodeFetch.Request as any;
|
||||
global.Headers = nodeFetch.Headers as any;
|
||||
});
|
||||
|
||||
|
||||
describe('client', () => {
|
||||
describe('::prepareRequest', () => {
|
||||
it('should prepare request successfully', () => {
|
||||
const client = new Client({
|
||||
baseUrl: 'https://example.org/api'
|
||||
});
|
||||
|
||||
const preparedRequest = client.prepareRequest({
|
||||
url: '/',
|
||||
method: Method.GET,
|
||||
headers: {},
|
||||
variables: {},
|
||||
});
|
||||
|
||||
expect(preparedRequest.url).toBe('https://example.org/api/');
|
||||
expect(preparedRequest.method).toBe(Method.GET);
|
||||
});
|
||||
|
||||
it('should prepare request successfully if client with relative base url', () => {
|
||||
const client = new Client({
|
||||
baseUrl: '/api'
|
||||
});
|
||||
|
||||
const preparedRequest = client.prepareRequest({
|
||||
url: '/',
|
||||
method: Method.GET,
|
||||
headers: {},
|
||||
variables: {},
|
||||
});
|
||||
|
||||
expect(preparedRequest.url).toBe('http://localhost/api/');
|
||||
expect(preparedRequest.method).toBe(Method.GET);
|
||||
});
|
||||
});
|
||||
});
|
|
@ -0,0 +1,99 @@
|
|||
import { formDataFromObject, isFunction, isObject, urlSearchParamsFromObject } from '../src/misc';
|
||||
|
||||
describe('misc', () => {
|
||||
describe('isObject', () => {
|
||||
it('should return thruthy successfully', () => {
|
||||
expect(isObject({})).toBeTruthy();
|
||||
});
|
||||
|
||||
it('should return falsy', () => {
|
||||
expect(isObject(1)).toBeFalsy();
|
||||
expect(isObject(true)).toBeFalsy();
|
||||
expect(isObject('')).toBeFalsy();
|
||||
expect(isObject([])).toBeFalsy();
|
||||
expect(isObject(function () { return null; })).toBeFalsy();
|
||||
expect(isObject(null)).toBeFalsy();
|
||||
expect(isObject(undefined)).toBeFalsy();
|
||||
expect(isObject(NaN)).toBeFalsy();
|
||||
expect(isObject(Infinity)).toBeFalsy();
|
||||
});
|
||||
});
|
||||
|
||||
describe('isFunction', () => {
|
||||
it('should return thruthy successfully', () => {
|
||||
expect(isFunction(function () { return null; })).toBeTruthy();
|
||||
});
|
||||
|
||||
it('should return falsy', () => {
|
||||
expect(isFunction(1)).toBeFalsy();
|
||||
expect(isFunction(true)).toBeFalsy();
|
||||
expect(isFunction('')).toBeFalsy();
|
||||
expect(isFunction([])).toBeFalsy();
|
||||
expect(isFunction({})).toBeFalsy();
|
||||
expect(isFunction(null)).toBeFalsy();
|
||||
expect(isFunction(undefined)).toBeFalsy();
|
||||
expect(isFunction(NaN)).toBeFalsy();
|
||||
expect(isFunction(Infinity)).toBeFalsy();
|
||||
});
|
||||
});
|
||||
|
||||
describe('formDataFromObject', () => {
|
||||
it('should convert object to form data successfully', () => {
|
||||
const formData = formDataFromObject({
|
||||
id: 1,
|
||||
name: 'John',
|
||||
status: ['ACTIVE', 'NOT_ACTIVE'],
|
||||
user: {
|
||||
name: 'John'
|
||||
}
|
||||
});
|
||||
|
||||
expect(formData).toBeInstanceOf(FormData);
|
||||
expect(formData.get('id')).toBe('1');
|
||||
expect(formData.get('name')).toBe('John');
|
||||
expect(formData.getAll('status')).toEqual(['ACTIVE', 'NOT_ACTIVE']);
|
||||
expect(formData.get('user')).toBe('{"name":"John"}');
|
||||
});
|
||||
|
||||
it('should filter undefined values successfully', () => {
|
||||
const formData = formDataFromObject({
|
||||
id: undefined,
|
||||
status: [undefined],
|
||||
});
|
||||
|
||||
expect(formData.has('id')).toBeFalsy();
|
||||
expect(formData.has('status')).toBeFalsy();
|
||||
});
|
||||
});
|
||||
|
||||
describe('urlSearchParamsFromObject', () => {
|
||||
it('should convert object to search params successfully', () => {
|
||||
const searchParams = urlSearchParamsFromObject({
|
||||
id: 1,
|
||||
name: 'John',
|
||||
status: ['ACTIVE', 'NOT_ACTIVE']
|
||||
});
|
||||
|
||||
expect(searchParams).toBeInstanceOf(URLSearchParams);
|
||||
expect(searchParams.toString()).toBe('id=1&name=John&status%5B%5D=ACTIVE&status%5B%5D=NOT_ACTIVE');
|
||||
});
|
||||
|
||||
it('should encode value as uri component successfully', () => {
|
||||
const searchParams = urlSearchParamsFromObject({
|
||||
name: '@',
|
||||
});
|
||||
|
||||
expect(searchParams.toString()).toBe('name=%40');
|
||||
});
|
||||
|
||||
it('should filter undefined values successfully', () => {
|
||||
const searchParams = urlSearchParamsFromObject({
|
||||
id: 1,
|
||||
name: undefined,
|
||||
status: ['ACTIVE', undefined],
|
||||
});
|
||||
|
||||
expect(searchParams.toString()).toBe('id=1&status%5B%5D=ACTIVE');
|
||||
});
|
||||
});
|
||||
});
|
|
@ -2,7 +2,7 @@
|
|||
"compilerOptions": {
|
||||
"rootDir": "src",
|
||||
"outDir": "target",
|
||||
"module": "esnext",
|
||||
"module": "commonjs",
|
||||
"target": "es6",
|
||||
"lib": ["dom", "es2020"],
|
||||
"jsx": "react",
|
||||
|
@ -14,9 +14,9 @@
|
|||
"strict": true,
|
||||
"strictNullChecks": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"declaration": true,
|
||||
"declaration": true
|
||||
},
|
||||
"include": [
|
||||
"src"
|
||||
],
|
||||
"src",
|
||||
]
|
||||
}
|
||||
|
|
Reference in New Issue