chore: build to commonjs
This commit is contained in:
parent
0f34ac9182
commit
56af2e57aa
11 changed files with 127 additions and 78 deletions
|
@ -1,3 +1,4 @@
|
|||
"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)
|
||||
|
@ -9,16 +10,18 @@ var __rest = (this && this.__rest) || function (s, e) {
|
|||
}
|
||||
return t;
|
||||
};
|
||||
import invariant from 'tiny-invariant';
|
||||
import { methodCanContainBody } from './endpoint';
|
||||
import { formDataFromObject, isFunction, urlSearchParamsFromObject } from './misc';
|
||||
export class Client {
|
||||
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 = methodCanContainBody(props.method);
|
||||
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
|
||||
|
@ -28,15 +31,15 @@ export class Client {
|
|||
}
|
||||
const url = new URL(sourceUrl, defaultBaseUrl);
|
||||
if (!requestCanContainBody) {
|
||||
invariant(!(props.variables instanceof FormData), `Method ${props.method} cannot contain body`);
|
||||
url.search = urlSearchParamsFromObject(props.variables).toString();
|
||||
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) : (formDataFromObject(props.variables))) : (
|
||||
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(), {
|
||||
|
@ -78,7 +81,7 @@ export class Client {
|
|||
url: res.url,
|
||||
error: 'error' in res ? res.error : undefined,
|
||||
canceled: 'canceled' in res ? res.canceled : false,
|
||||
data: isFunction(transformResponseData) ? transformResponseData(data) : data,
|
||||
data: misc_1.isFunction(transformResponseData) ? transformResponseData(data) : data,
|
||||
};
|
||||
})
|
||||
.then((res) => {
|
||||
|
@ -89,3 +92,4 @@ export class Client {
|
|||
});
|
||||
}
|
||||
}
|
||||
exports.Client = Client;
|
||||
|
|
2
target/client_hook.d.ts
vendored
2
target/client_hook.d.ts
vendored
|
@ -1 +1 @@
|
|||
export declare function useClient(): import("./client").Client[];
|
||||
export declare function useClient(): readonly [import("./client").Client];
|
||||
|
|
|
@ -1,5 +1,9 @@
|
|||
import { useRequestContext } from './request_context';
|
||||
export function useClient() {
|
||||
const { client } = useRequestContext();
|
||||
"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;
|
||||
|
|
|
@ -1,4 +1,7 @@
|
|||
export var Method;
|
||||
"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";
|
||||
|
@ -6,10 +9,12 @@ export var Method;
|
|||
Method["POST"] = "POST";
|
||||
Method["PATCH"] = "PATCH";
|
||||
Method["DELETE"] = "DELETE";
|
||||
})(Method || (Method = {}));
|
||||
export function methodCanContainBody(method) {
|
||||
})(Method = exports.Method || (exports.Method = {}));
|
||||
function methodCanContainBody(method) {
|
||||
return [Method.POST, Method.PATCH, Method.PUT].includes(method);
|
||||
}
|
||||
export function methodWithoutEffects(method) {
|
||||
exports.methodCanContainBody = methodCanContainBody;
|
||||
function methodWithoutEffects(method) {
|
||||
return [Method.HEAD, Method.GET].includes(method);
|
||||
}
|
||||
exports.methodWithoutEffects = methodWithoutEffects;
|
||||
|
|
|
@ -1,7 +1,19 @@
|
|||
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';
|
||||
"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);
|
||||
|
|
|
@ -1,24 +1,27 @@
|
|||
import React from 'react';
|
||||
import invariant from 'tiny-invariant';
|
||||
import isEqual from 'lodash.isequal';
|
||||
import { useClient } from './client_hook';
|
||||
import { methodWithoutEffects } from './endpoint';
|
||||
import { INITIAL_REQUEST_STATE, requestReducer } from './reducer';
|
||||
import { useRequestContext } from './request_context';
|
||||
import { isFunction } from './misc';
|
||||
"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");
|
||||
;
|
||||
export function useLazyRequest(endpoint, config) {
|
||||
const [client] = useClient();
|
||||
const { defaultHeaders } = useRequestContext();
|
||||
const [state, dispatch] = React.useReducer(requestReducer, INITIAL_REQUEST_STATE);
|
||||
const [prevHandlerConfig, setPrevHandlerConfig] = React.useState(null);
|
||||
const abortControllerRef = React.useRef(new AbortController());
|
||||
const transformResponseData = React.useCallback((data) => {
|
||||
return isFunction(endpoint.transformResponseData) ?
|
||||
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.useCallback((handlerConfig) => {
|
||||
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);
|
||||
|
@ -26,28 +29,28 @@ export function useLazyRequest(endpoint, config) {
|
|||
let params;
|
||||
let endpointUrl;
|
||||
let isSameRequest = true;
|
||||
if (isFunction(endpoint.url)) {
|
||||
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;
|
||||
invariant(params, 'Endpoint required params');
|
||||
tiny_invariant_1.default(params, 'Endpoint required params');
|
||||
endpointUrl = endpoint.url(params);
|
||||
isSameRequest = !!(state === null || state === void 0 ? void 0 : state.prevParams) && isEqual(state.prevParams, 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 = (methodWithoutEffects(endpoint.method)
|
||||
const shouldReturnCachedValue = (endpoint_1.methodWithoutEffects(endpoint.method)
|
||||
&& state.isCalled
|
||||
&& isSameRequest
|
||||
&& (state === null || state === void 0 ? void 0 : state.prevVariables) && isEqual(state.prevVariables, variables)
|
||||
&& (state === null || state === void 0 ? void 0 : state.prevHeaders) && isEqual(state.prevHeaders, headers)
|
||||
&& (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(isFunction);
|
||||
const onFailures = [config === null || config === void 0 ? void 0 : config.onFailure, handlerConfig === null || handlerConfig === void 0 ? void 0 : handlerConfig.onFailure].filter(isFunction);
|
||||
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
|
||||
|
@ -66,20 +69,20 @@ export function useLazyRequest(endpoint, config) {
|
|||
return null;
|
||||
});
|
||||
}, [state, config, client, endpoint, defaultHeaders, transformResponseData]);
|
||||
const refetchRequest = React.useCallback(() => {
|
||||
const refetchRequest = react_1.default.useCallback(() => {
|
||||
if (prevHandlerConfig != null) {
|
||||
handler(Object.assign({}, prevHandlerConfig));
|
||||
}
|
||||
}, [handler, prevHandlerConfig]);
|
||||
const cancelRequest = React.useCallback(() => {
|
||||
const cancelRequest = react_1.default.useCallback(() => {
|
||||
dispatch({ type: 'cancel' });
|
||||
abortControllerRef.current.abort();
|
||||
abortControllerRef.current = new AbortController();
|
||||
}, []);
|
||||
const clearRequestStore = React.useCallback(() => {
|
||||
const clearRequestStore = react_1.default.useCallback(() => {
|
||||
dispatch({ type: 'clearStore' });
|
||||
}, []);
|
||||
React.useEffect(() => cancelRequest, [cancelRequest]);
|
||||
react_1.default.useEffect(() => cancelRequest, [cancelRequest]);
|
||||
return [
|
||||
handler,
|
||||
{
|
||||
|
@ -94,3 +97,4 @@ export function useLazyRequest(endpoint, config) {
|
|||
},
|
||||
];
|
||||
}
|
||||
exports.useLazyRequest = useLazyRequest;
|
||||
|
|
|
@ -1,10 +1,15 @@
|
|||
export function isObject(val) {
|
||||
"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]';
|
||||
}
|
||||
export function isFunction(val) {
|
||||
exports.isObject = isObject;
|
||||
function isFunction(val) {
|
||||
return typeof val === 'function';
|
||||
}
|
||||
export function formDataFromObject(obj) {
|
||||
exports.isFunction = isFunction;
|
||||
function formDataFromObject(obj) {
|
||||
const formData = new FormData();
|
||||
Object.entries(obj)
|
||||
.filter(([_, value]) => value !== undefined)
|
||||
|
@ -23,7 +28,8 @@ export function formDataFromObject(obj) {
|
|||
});
|
||||
return formData;
|
||||
}
|
||||
export function urlSearchParamsFromObject(obj) {
|
||||
exports.formDataFromObject = formDataFromObject;
|
||||
function urlSearchParamsFromObject(obj) {
|
||||
const searchParams = new URLSearchParams();
|
||||
Object.entries(obj)
|
||||
.filter(([_, value]) => value !== undefined)
|
||||
|
@ -40,3 +46,4 @@ export function urlSearchParamsFromObject(obj) {
|
|||
});
|
||||
return searchParams;
|
||||
}
|
||||
exports.urlSearchParamsFromObject = urlSearchParamsFromObject;
|
||||
|
|
|
@ -1,4 +1,7 @@
|
|||
export const INITIAL_REQUEST_STATE = {
|
||||
"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,
|
||||
|
@ -9,7 +12,7 @@ export const INITIAL_REQUEST_STATE = {
|
|||
prevVariables: undefined,
|
||||
prevParams: undefined,
|
||||
};
|
||||
export function requestReducer(state, action) {
|
||||
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 });
|
||||
|
@ -24,7 +27,8 @@ export function requestReducer(state, action) {
|
|||
return Object.assign(Object.assign({}, state), { isCanceled: true, fetchError: undefined });
|
||||
}
|
||||
case 'clearStore': {
|
||||
return INITIAL_REQUEST_STATE;
|
||||
return exports.INITIAL_REQUEST_STATE;
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.requestReducer = requestReducer;
|
||||
|
|
|
@ -1,11 +1,16 @@
|
|||
import React from 'react';
|
||||
import invariant from 'tiny-invariant';
|
||||
const RequestContext = React.createContext(null);
|
||||
export function RequestProvider({ client, defaultHeaders, children }) {
|
||||
return (React.createElement(RequestContext.Provider, { value: { client, defaultHeaders } }, children));
|
||||
"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));
|
||||
}
|
||||
export function useRequestContext() {
|
||||
const context = React.useContext(RequestContext);
|
||||
invariant(context, 'useRequestContext() must be a child of <RequestProvider />');
|
||||
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;
|
||||
|
|
|
@ -1,15 +1,19 @@
|
|||
import React from 'react';
|
||||
import invariant from 'tiny-invariant';
|
||||
import { methodWithoutEffects } from './endpoint';
|
||||
import { useLazyRequest } from './lazy_request_hook';
|
||||
export function useRequest(endpoint, config) {
|
||||
invariant(methodWithoutEffects(endpoint.method), `You cannot use useRequest with ${endpoint.method} method`);
|
||||
const [handler, state] = useLazyRequest(endpoint, config);
|
||||
const skip = React.useMemo(() => { var _a; return (_a = config === null || config === void 0 ? void 0 : config.skip) !== null && _a !== void 0 ? _a : false; }, [config]);
|
||||
React.useEffect(() => {
|
||||
"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;
|
||||
|
|
|
@ -2,7 +2,7 @@
|
|||
"compilerOptions": {
|
||||
"rootDir": "src",
|
||||
"outDir": "target",
|
||||
"module": "esnext",
|
||||
"module": "commonjs",
|
||||
"target": "es6",
|
||||
"lib": ["dom", "es2020"],
|
||||
"jsx": "react",
|
||||
|
|
Reference in a new issue