@koine/api 2.0.0-beta.5 → 2.0.0-beta.51
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.cjs.d.ts +1 -0
- package/index.cjs.default.js +1 -0
- package/index.cjs.js +12 -0
- package/index.cjs.mjs +2 -0
- package/index.d.ts +6 -4
- package/index.esm.js +5 -0
- package/next.cjs.d.ts +1 -0
- package/next.cjs.default.js +1 -0
- package/next.cjs.js +12 -0
- package/next.cjs.mjs +2 -0
- package/next.d.ts +10 -0
- package/next.esm.js +7 -0
- package/package.json +33 -15
- package/swr-mutation.cjs.d.ts +1 -0
- package/swr-mutation.cjs.default.js +1 -0
- package/swr-mutation.cjs.js +17 -0
- package/swr-mutation.cjs.mjs +2 -0
- package/swr-mutation.d.ts +16 -0
- package/swr-mutation.esm.js +9 -0
- package/swr.cjs.d.ts +1 -0
- package/swr.cjs.default.js +1 -0
- package/swr.cjs.js +16 -0
- package/swr.cjs.mjs +2 -0
- package/swr.d.ts +9 -0
- package/swr.esm.js +7 -0
- package/typings.d.ts +55 -31
- package/ApiError.d.ts +0 -11
- package/ApiError.js +0 -32
- package/ApiError.mjs +0 -14
- package/createApi.d.ts +0 -8
- package/createApi.js +0 -142
- package/createApi.mjs +0 -128
- package/createSwrApi.d.ts +0 -34
- package/createSwrApi.js +0 -99
- package/createSwrApi.mjs +0 -82
- package/index.js +0 -28
- package/index.mjs +0 -4
- package/nextApiResponse.d.ts +0 -3
- package/nextApiResponse.js +0 -23
- package/nextApiResponse.mjs +0 -5
package/index.cjs.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./index";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
exports._default = require('./index.cjs.js').default;
|
package/index.cjs.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, '__esModule', { value: true });
|
|
4
|
+
|
|
5
|
+
var utils = require('@koine/utils');
|
|
6
|
+
|
|
7
|
+
class ApiError extends Error{constructor(e){super(`Request failed with ${e.status} ${e.msg}`),this.name="ApiError",Object.assign(this,e);}}let createApiResultOk=(e={},t)=>({ok:!0,fail:!1,data:e,msg:t||"",status:200});let createApiResultFail=(e={},t,r)=>({fail:!0,data:e,msg:t||"",status:r||404});let s=["get","post","put","patch","delete"];let createApi=(o,a,l)=>{let{headers:i={},request:n={},throwErr:p,timeout:c=1e4,processReq:u,processRes:f,processErr:h}=l||{};return s.reduce((s,l)=>(s[l]=async(s,m)=>{let $,d;let{request:g=n,headers:w=i,timeout:E=c,processReq:y,processRes:A=f,processErr:b=h,throwErr:k=p}=m||{},{params:x,json:R,query:N}=m||{},O=`${a}/${s+"".replace(/^\/*/,"")}`,j={method:l.toUpperCase(),...g,headers:{"content-type":"application/json",...w}};if(u){let e=u(l,O,N,R,x,j);O=e[0],N=e[1],R=e[2],x=e[3],j=e[4];}if(y){let e=y(l,O,N,R,x,j);O=e[0],N=e[1],R=e[2],x=e[3],j=e[4];}if(utils.isFullObject(x))for(let e in x)O=O.replace(`{${e}}`,x[e].toString());let q=Number(E);R&&(j.body=JSON.stringify(R)),q>0&&($=new AbortController,d=setTimeout(()=>$.abort(),q),j.signal=$.signal),N&&(O+=utils.buildUrlQueryString(N));let C=null,v=null,S="";try{C=await fetch(O,j);}catch(e){S=utils.errorToString(e);}if(d&&clearTimeout(d),C)try{v=A?await A(C,m||{}):await C.json();}catch(e){S=utils.errorToString(e);}if(null===v&&(v=b?await b(S,m||{}):{data:null,msg:S,status:100,fail:!0,ok:!1}),k&&v?.fail)throw v;if("development"===process.env.NODE_ENV){let e=`${v?.status}: api[${o}] ${l.toUpperCase()} ${O}`;v?.ok?console.info(`🟢 ${e}`):console.info(`🔴 ${e}`);}return v},s),{})};
|
|
8
|
+
|
|
9
|
+
exports.ApiError = ApiError;
|
|
10
|
+
exports.createApi = createApi;
|
|
11
|
+
exports.createApiResultFail = createApiResultFail;
|
|
12
|
+
exports.createApiResultOk = createApiResultOk;
|
package/index.cjs.mjs
ADDED
package/index.d.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
export
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
export
|
|
1
|
+
export declare class ApiError<TResponseFail extends Koine.Api.ResponseFail = unknown> extends Error {
|
|
2
|
+
constructor(result: Koine.Api.ResultFail<TResponseFail>);
|
|
3
|
+
}
|
|
4
|
+
export declare let createApiResultOk: <T>(data?: T, msg?: string) => Koine.Api.ResultOk<T>;
|
|
5
|
+
export declare let createApiResultFail: <T>(data?: T, msg?: string, status?: number) => Koine.Api.ResultFail<T>;
|
|
6
|
+
export declare let createApi: <TEndpoints extends Koine.Api.Endpoints>(apiName: string, baseUrl: string, options?: Koine.Api.ClientOptions) => Koine.Api.Client<TEndpoints>;
|
package/index.esm.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { isFullObject, buildUrlQueryString, errorToString } from '@koine/utils';
|
|
2
|
+
|
|
3
|
+
class ApiError extends Error{constructor(e){super(`Request failed with ${e.status} ${e.msg}`),this.name="ApiError",Object.assign(this,e);}}let createApiResultOk=(e={},t)=>({ok:!0,fail:!1,data:e,msg:t||"",status:200});let createApiResultFail=(e={},t,r)=>({fail:!0,data:e,msg:t||"",status:r||404});let s=["get","post","put","patch","delete"];let createApi=(o,a,l)=>{let{headers:i={},request:n={},throwErr:p,timeout:c=1e4,processReq:u,processRes:f,processErr:h}=l||{};return s.reduce((s,l)=>(s[l]=async(s,m)=>{let $,d;let{request:g=n,headers:w=i,timeout:E=c,processReq:y,processRes:A=f,processErr:b=h,throwErr:k=p}=m||{},{params:x,json:R,query:N}=m||{},O=`${a}/${s+"".replace(/^\/*/,"")}`,j={method:l.toUpperCase(),...g,headers:{"content-type":"application/json",...w}};if(u){let e=u(l,O,N,R,x,j);O=e[0],N=e[1],R=e[2],x=e[3],j=e[4];}if(y){let e=y(l,O,N,R,x,j);O=e[0],N=e[1],R=e[2],x=e[3],j=e[4];}if(isFullObject(x))for(let e in x)O=O.replace(`{${e}}`,x[e].toString());let q=Number(E);R&&(j.body=JSON.stringify(R)),q>0&&($=new AbortController,d=setTimeout(()=>$.abort(),q),j.signal=$.signal),N&&(O+=buildUrlQueryString(N));let C=null,v=null,S="";try{C=await fetch(O,j);}catch(e){S=errorToString(e);}if(d&&clearTimeout(d),C)try{v=A?await A(C,m||{}):await C.json();}catch(e){S=errorToString(e);}if(null===v&&(v=b?await b(S,m||{}):{data:null,msg:S,status:100,fail:!0,ok:!1}),k&&v?.fail)throw v;if("development"===process.env.NODE_ENV){let e=`${v?.status}: api[${o}] ${l.toUpperCase()} ${O}`;v?.ok?console.info(`🟢 ${e}`):console.info(`🔴 ${e}`);}return v},s),{})};
|
|
4
|
+
|
|
5
|
+
export { ApiError, createApi, createApiResultFail, createApiResultOk };
|
package/next.cjs.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./next";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
exports._default = require('./next.cjs.js').default;
|
package/next.cjs.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, '__esModule', { value: true });
|
|
4
|
+
|
|
5
|
+
var server = require('next/server');
|
|
6
|
+
var index = require('./index.cjs.js');
|
|
7
|
+
require('@koine/utils');
|
|
8
|
+
|
|
9
|
+
let nextApiResponse={ok:(o,t)=>server.NextResponse.json(index.createApiResultOk(o,t)),fail:(s,t,n)=>server.NextResponse.json(index.createApiResultFail(s,t,n))};let nextApiResponse12=e=>({ok(o,t){e.status(200).json(index.createApiResultOk(o,t));},fail(s,t,n){e.status(n||404).json(index.createApiResultFail(s,t,n));}});
|
|
10
|
+
|
|
11
|
+
exports.nextApiResponse = nextApiResponse;
|
|
12
|
+
exports.nextApiResponse12 = nextApiResponse12;
|
package/next.cjs.mjs
ADDED
package/next.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { NextApiResponse } from "next";
|
|
2
|
+
import { NextResponse } from "next/server";
|
|
3
|
+
export declare let nextApiResponse: {
|
|
4
|
+
ok<T>(data: T, msg?: string): NextResponse<Koine.Api.ResultOk<T>>;
|
|
5
|
+
fail<T_1>(data: T_1, msg?: string, status?: number): NextResponse<Koine.Api.ResultFail<T_1>>;
|
|
6
|
+
};
|
|
7
|
+
export declare let nextApiResponse12: (nextRes: NextApiResponse) => {
|
|
8
|
+
ok<T>(data: T, msg?: string): void;
|
|
9
|
+
fail<T_1>(data: T_1, msg?: string, status?: number): void;
|
|
10
|
+
};
|
package/next.esm.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { NextResponse } from 'next/server';
|
|
2
|
+
import { createApiResultOk, createApiResultFail } from './index.esm.js';
|
|
3
|
+
import '@koine/utils';
|
|
4
|
+
|
|
5
|
+
let nextApiResponse={ok:(o,t)=>NextResponse.json(createApiResultOk(o,t)),fail:(s,t,n)=>NextResponse.json(createApiResultFail(s,t,n))};let nextApiResponse12=e=>({ok(o,t){e.status(200).json(createApiResultOk(o,t));},fail(s,t,n){e.status(n||404).json(createApiResultFail(s,t,n));}});
|
|
6
|
+
|
|
7
|
+
export { nextApiResponse, nextApiResponse12 };
|
package/package.json
CHANGED
|
@@ -1,27 +1,45 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@koine/api",
|
|
3
3
|
"sideEffects": false,
|
|
4
|
+
"dependencies": {
|
|
5
|
+
"@koine/utils": "2.0.0-beta.51"
|
|
6
|
+
},
|
|
7
|
+
"peerDependencies": {
|
|
8
|
+
"next": "^14.0.4",
|
|
9
|
+
"swr": "^2.2.4"
|
|
10
|
+
},
|
|
4
11
|
"peerDependenciesMeta": {
|
|
5
12
|
"next": {
|
|
6
13
|
"optional": true
|
|
14
|
+
},
|
|
15
|
+
"swr": {
|
|
16
|
+
"optional": true
|
|
7
17
|
}
|
|
8
18
|
},
|
|
9
|
-
"dependencies": {
|
|
10
|
-
"clsx": "^1.2.1",
|
|
11
|
-
"next": "^13.4.7",
|
|
12
|
-
"swr": "^2.2.0",
|
|
13
|
-
"ts-debounce": "^4.0.0",
|
|
14
|
-
"type-fest": "^3.12.0"
|
|
15
|
-
},
|
|
16
|
-
"peerDependencies": {},
|
|
17
|
-
"module": "./index.mjs",
|
|
18
|
-
"main": "./index.js",
|
|
19
19
|
"exports": {
|
|
20
|
+
"./package.json": "./package.json",
|
|
20
21
|
".": {
|
|
21
|
-
"
|
|
22
|
-
"
|
|
22
|
+
"module": "./index.esm.js",
|
|
23
|
+
"import": "./index.cjs.mjs",
|
|
24
|
+
"default": "./index.cjs.js"
|
|
25
|
+
},
|
|
26
|
+
"./next": {
|
|
27
|
+
"module": "./next.esm.js",
|
|
28
|
+
"import": "./next.cjs.mjs",
|
|
29
|
+
"default": "./next.cjs.js"
|
|
30
|
+
},
|
|
31
|
+
"./swr-mutation": {
|
|
32
|
+
"module": "./swr-mutation.esm.js",
|
|
33
|
+
"import": "./swr-mutation.cjs.mjs",
|
|
34
|
+
"default": "./swr-mutation.cjs.js"
|
|
35
|
+
},
|
|
36
|
+
"./swr": {
|
|
37
|
+
"module": "./swr.esm.js",
|
|
38
|
+
"import": "./swr.cjs.mjs",
|
|
39
|
+
"default": "./swr.cjs.js"
|
|
23
40
|
}
|
|
24
41
|
},
|
|
25
|
-
"
|
|
26
|
-
"
|
|
27
|
-
|
|
42
|
+
"module": "./index.esm.js",
|
|
43
|
+
"main": "./index.cjs.js",
|
|
44
|
+
"version": "2.0.0-beta.51"
|
|
45
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./swr-mutation";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
exports._default = require('./swr-mutation.cjs.js').default;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, '__esModule', { value: true });
|
|
4
|
+
|
|
5
|
+
var r = require('swr/mutation');
|
|
6
|
+
var index = require('./index.cjs.js');
|
|
7
|
+
var swr = require('./swr.cjs.js');
|
|
8
|
+
require('@koine/utils');
|
|
9
|
+
require('swr');
|
|
10
|
+
|
|
11
|
+
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
|
|
12
|
+
|
|
13
|
+
var r__default = /*#__PURE__*/_interopDefaultLegacy(r);
|
|
14
|
+
|
|
15
|
+
let a=(t,e)=>(a,o,i)=>r__default["default"](o?[a,o]:a,async(r,a)=>{let o=Array.isArray(r)?r[0]:r,i=Array.isArray(r)?r[1]:{},{ok:p,data:s}=await t[e](o,{...i,...a.arg||{},throwErr:!0});return s},i);let createSwrMutationApi=(...r)=>{let o=index.createApi(...r);return o.use=swr.createUseApi(o),["post","put","patch","delete"].forEach(r=>{o[`use${r.charAt(0).toUpperCase()+r.slice(1)}`]=a(o,r);}),o};
|
|
16
|
+
|
|
17
|
+
exports.createSwrMutationApi = createSwrMutationApi;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { type SWRMutationConfiguration, type SWRMutationResponse } from "swr/mutation";
|
|
2
|
+
import { createUseApi } from "./swr";
|
|
3
|
+
type MutationRequestMethod = Exclude<Koine.Api.RequestMethod, "get">;
|
|
4
|
+
type MutationHookName = Exclude<keyof Koine.Api.HooksMapsByName, "use">;
|
|
5
|
+
type KoineApiMethodHookSWR<THookName extends MutationHookName, TEndpoints extends Koine.Api.Endpoints> = <TEndpoint extends Koine.Api.EndpointUrl<TEndpoints>, TMethod extends MutationRequestMethod = Koine.Api.HooksMapsByName[THookName]>(endpoint: TEndpoint, options?: Koine.Api.EndpointOptions<TEndpoints, TEndpoint, TMethod>, config?: SWRMutationConfiguration<Koine.Api.EndpointResponseOk<TEndpoints, TEndpoint, TMethod>, Koine.Api.EndpointResponseFail<TEndpoints, TEndpoint, TMethod>, TEndpoint, Koine.Api.EndpointOptions<TEndpoints, TEndpoint, TMethod>>) => SWRMutationResponse<Koine.Api.EndpointResponseOk<TEndpoints, TEndpoint, TMethod>, Koine.Api.EndpointResponseFail<TEndpoints, TEndpoint, TMethod>, TEndpoint, Koine.Api.EndpointOptions<TEndpoints, TEndpoint, TMethod>>;
|
|
6
|
+
export declare let createSwrMutationApi: <TEndpoints extends Koine.Api.Endpoints>(apiName: string, baseUrl: string, options?: Koine.Api.ClientOptions | undefined) => Koine.Api.Client<TEndpoints> & {
|
|
7
|
+
usePost: KoineApiMethodHookSWR<"usePost", TEndpoints>;
|
|
8
|
+
usePut: KoineApiMethodHookSWR<"usePut", TEndpoints>;
|
|
9
|
+
usePatch: KoineApiMethodHookSWR<"usePatch", TEndpoints>;
|
|
10
|
+
useDelete: KoineApiMethodHookSWR<"useDelete", TEndpoints>;
|
|
11
|
+
} & {
|
|
12
|
+
use: <TEndpoint extends Extract<keyof TEndpoints, string>>(endpoint: TEndpoint, options?: Koine.Api.EndpointOptions<TEndpoints, TEndpoint, "get"> | undefined, config?: (Partial<import("swr/_internal").PublicConfiguration<Koine.Api.EndpointResponseOk<TEndpoints, TEndpoint, "get">, Koine.Api.EndpointResponseFail<TEndpoints, TEndpoint, "get">, import("swr/_internal").BareFetcher<any>>> & {
|
|
13
|
+
when?: boolean | (() => boolean) | undefined;
|
|
14
|
+
}) | undefined) => import("swr/_internal").SWRResponse<Koine.Api.EndpointResponseOk<TEndpoints, TEndpoint, "get">, Koine.Api.EndpointResponseFail<TEndpoints, TEndpoint, "get">, any>;
|
|
15
|
+
};
|
|
16
|
+
export {};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import r from 'swr/mutation';
|
|
2
|
+
import { createApi } from './index.esm.js';
|
|
3
|
+
import { createUseApi } from './swr.esm.js';
|
|
4
|
+
import '@koine/utils';
|
|
5
|
+
import 'swr';
|
|
6
|
+
|
|
7
|
+
let a=(t,e)=>(a,o,i)=>r(o?[a,o]:a,async(r,a)=>{let o=Array.isArray(r)?r[0]:r,i=Array.isArray(r)?r[1]:{},{ok:p,data:s}=await t[e](o,{...i,...a.arg||{},throwErr:!0});return s},i);let createSwrMutationApi=(...r)=>{let o=createApi(...r);return o.use=createUseApi(o),["post","put","patch","delete"].forEach(r=>{o[`use${r.charAt(0).toUpperCase()+r.slice(1)}`]=a(o,r);}),o};
|
|
8
|
+
|
|
9
|
+
export { createSwrMutationApi };
|
package/swr.cjs.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./swr";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
exports._default = require('./swr.cjs.js').default;
|
package/swr.cjs.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, '__esModule', { value: true });
|
|
4
|
+
|
|
5
|
+
var e = require('swr');
|
|
6
|
+
var utils = require('@koine/utils');
|
|
7
|
+
var index = require('./index.cjs.js');
|
|
8
|
+
|
|
9
|
+
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
|
|
10
|
+
|
|
11
|
+
var e__default = /*#__PURE__*/_interopDefaultLegacy(e);
|
|
12
|
+
|
|
13
|
+
let createUseApi=t=>(i,n,o)=>{let l=async()=>{let{data:e}=await t.get(i,{...n||{},throwErr:!0});return e};return e__default["default"](o?.when===!1||utils.isFunction(o?.when)&&o?.when()===!1?null:n?[i,n]:[i],l,o)};let createSwrApi=(...e)=>{let r=index.createApi(...e);return r.use=createUseApi(r),r};
|
|
14
|
+
|
|
15
|
+
exports.createSwrApi = createSwrApi;
|
|
16
|
+
exports.createUseApi = createUseApi;
|
package/swr.cjs.mjs
ADDED
package/swr.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { type BareFetcher, type SWRConfiguration, type SWRResponse } from "swr";
|
|
2
|
+
type SWRConfigurationExtended<Data = any, Error = any, Fn extends BareFetcher<any> = BareFetcher<any>> = SWRConfiguration<Data, Error, Fn> & {
|
|
3
|
+
when?: boolean | (() => boolean);
|
|
4
|
+
};
|
|
5
|
+
export declare let createUseApi: <TEndpoints extends Koine.Api.Endpoints>(api: Koine.Api.Client<TEndpoints>) => <TEndpoint extends Extract<keyof TEndpoints, string>>(endpoint: TEndpoint, options?: Koine.Api.EndpointOptions<TEndpoints, TEndpoint, "get"> | undefined, config?: SWRConfigurationExtended<Koine.Api.EndpointResponseOk<TEndpoints, TEndpoint, "get">, Koine.Api.EndpointResponseFail<TEndpoints, TEndpoint, "get">, BareFetcher<any>> | undefined) => SWRResponse<Koine.Api.EndpointResponseOk<TEndpoints, TEndpoint, "get">, Koine.Api.EndpointResponseFail<TEndpoints, TEndpoint, "get">, any>;
|
|
6
|
+
export declare let createSwrApi: <TEndpoints extends Koine.Api.Endpoints>(apiName: string, baseUrl: string, options?: Koine.Api.ClientOptions | undefined) => Koine.Api.Client<TEndpoints> & {
|
|
7
|
+
use: <TEndpoint extends Extract<keyof TEndpoints, string>>(endpoint: TEndpoint, options?: Koine.Api.EndpointOptions<TEndpoints, TEndpoint, "get"> | undefined, config?: SWRConfigurationExtended<Koine.Api.EndpointResponseOk<TEndpoints, TEndpoint, "get">, Koine.Api.EndpointResponseFail<TEndpoints, TEndpoint, "get">, BareFetcher<any>> | undefined) => SWRResponse<Koine.Api.EndpointResponseOk<TEndpoints, TEndpoint, "get">, Koine.Api.EndpointResponseFail<TEndpoints, TEndpoint, "get">, any>;
|
|
8
|
+
};
|
|
9
|
+
export {};
|
package/swr.esm.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import e from 'swr';
|
|
2
|
+
import { isFunction } from '@koine/utils';
|
|
3
|
+
import { createApi } from './index.esm.js';
|
|
4
|
+
|
|
5
|
+
let createUseApi=t=>(i,n,o)=>{let l=async()=>{let{data:e}=await t.get(i,{...n||{},throwErr:!0});return e};return e(o?.when===!1||isFunction(o?.when)&&o?.when()===!1?null:n?[i,n]:[i],l,o)};let createSwrApi=(...e)=>{let r=createApi(...e);return r.use=createUseApi(r),r};
|
|
6
|
+
|
|
7
|
+
export { createSwrApi, createUseApi };
|
package/typings.d.ts
CHANGED
|
@@ -8,14 +8,14 @@ type _Response = Response;
|
|
|
8
8
|
type ExtractEndpointParams<T extends string> = string extends T
|
|
9
9
|
? Record<string, string>
|
|
10
10
|
: // eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
11
|
+
T extends `${infer _Start}{${infer Param}}${infer Rest}`
|
|
12
|
+
? { [k in Param | keyof ExtractEndpointParams<Rest>]: string | number }
|
|
13
|
+
: // eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
14
|
+
T extends `${infer _Start}{${infer Param}}`
|
|
15
|
+
? { [k in Param]: string | number }
|
|
16
|
+
: never;
|
|
17
|
+
|
|
18
|
+
namespace Koine.Api {
|
|
19
19
|
// @see https://stackoverflow.com/a/60702896/1938970
|
|
20
20
|
// import { Exact } from "type-fest";
|
|
21
21
|
|
|
@@ -28,7 +28,7 @@ declare namespace Koine.Api {
|
|
|
28
28
|
type ClientCreator<TEndpoints extends Endpoints> = (
|
|
29
29
|
apiName: string,
|
|
30
30
|
baseUrl: string,
|
|
31
|
-
options?: ClientOptions
|
|
31
|
+
options?: ClientOptions,
|
|
32
32
|
) => Client<TEndpoints>;
|
|
33
33
|
|
|
34
34
|
type ClientOptions = {
|
|
@@ -46,7 +46,7 @@ declare namespace Koine.Api {
|
|
|
46
46
|
*
|
|
47
47
|
* @see RequestInit
|
|
48
48
|
*
|
|
49
|
-
* @default {
|
|
49
|
+
* @default {}
|
|
50
50
|
*/
|
|
51
51
|
request?: Omit<RequestInit, "body" | "headers" | "method">;
|
|
52
52
|
/**
|
|
@@ -85,7 +85,7 @@ declare namespace Koine.Api {
|
|
|
85
85
|
|
|
86
86
|
type ClientMethod<
|
|
87
87
|
TMethod extends RequestMethod,
|
|
88
|
-
TEndpoints extends Endpoints
|
|
88
|
+
TEndpoints extends Endpoints,
|
|
89
89
|
> = <
|
|
90
90
|
TEndpoint extends EndpointUrl<TEndpoints>,
|
|
91
91
|
TOptions extends EndpointOptions<TEndpoints, TEndpoint, TMethod>,
|
|
@@ -94,10 +94,10 @@ declare namespace Koine.Api {
|
|
|
94
94
|
TEndpoints,
|
|
95
95
|
TEndpoint,
|
|
96
96
|
TMethod
|
|
97
|
-
|
|
97
|
+
>,
|
|
98
98
|
>(
|
|
99
99
|
endpoint: TEndpoint,
|
|
100
|
-
options?: TOptions
|
|
100
|
+
options?: TOptions,
|
|
101
101
|
) => Promise<EndpointResult<TEndpoints, TEndpoint, TMethod>>;
|
|
102
102
|
// ) => Promise<Result<TOk, TFail>>;
|
|
103
103
|
|
|
@@ -117,7 +117,7 @@ declare namespace Koine.Api {
|
|
|
117
117
|
type EndpointOptions<
|
|
118
118
|
TEndpoints extends Endpoints,
|
|
119
119
|
TEndpoint extends EndpointUrl<TEndpoints>,
|
|
120
|
-
TMethod extends RequestMethod
|
|
120
|
+
TMethod extends RequestMethod,
|
|
121
121
|
> = RequestOptions<
|
|
122
122
|
TEndpoints,
|
|
123
123
|
TEndpoint,
|
|
@@ -129,31 +129,31 @@ declare namespace Koine.Api {
|
|
|
129
129
|
type EndpointResultOk<
|
|
130
130
|
TEndpoints extends Endpoints,
|
|
131
131
|
TEndpoint extends EndpointUrl<TEndpoints>,
|
|
132
|
-
TMethod extends RequestMethod
|
|
132
|
+
TMethod extends RequestMethod,
|
|
133
133
|
> = ResultOk<TEndpoints[TEndpoint][Uppercase<TMethod>]["ok"]>;
|
|
134
134
|
|
|
135
135
|
type EndpointResultFail<
|
|
136
136
|
TEndpoints extends Endpoints,
|
|
137
137
|
TEndpoint extends EndpointUrl<TEndpoints>,
|
|
138
|
-
TMethod extends RequestMethod
|
|
138
|
+
TMethod extends RequestMethod,
|
|
139
139
|
> = ResultFail<TEndpoints[TEndpoint][Uppercase<TMethod>]["fail"]>;
|
|
140
140
|
|
|
141
141
|
type EndpointResponseOk<
|
|
142
142
|
TEndpoints extends Endpoints,
|
|
143
143
|
TEndpoint extends EndpointUrl<TEndpoints>,
|
|
144
|
-
TMethod extends RequestMethod
|
|
144
|
+
TMethod extends RequestMethod,
|
|
145
145
|
> = TEndpoints[TEndpoint][Uppercase<TMethod>]["ok"];
|
|
146
146
|
|
|
147
147
|
type EndpointResponseFail<
|
|
148
148
|
TEndpoints extends Endpoints,
|
|
149
149
|
TEndpoint extends EndpointUrl<TEndpoints>,
|
|
150
|
-
TMethod extends RequestMethod
|
|
150
|
+
TMethod extends RequestMethod,
|
|
151
151
|
> = TEndpoints[TEndpoint][Uppercase<TMethod>]["fail"];
|
|
152
152
|
|
|
153
153
|
type EndpointResult<
|
|
154
154
|
TEndpoints extends Endpoints,
|
|
155
155
|
TEndpoint extends EndpointUrl<TEndpoints>,
|
|
156
|
-
TMethod extends RequestMethod
|
|
156
|
+
TMethod extends RequestMethod,
|
|
157
157
|
> = Result<
|
|
158
158
|
EndpointResponseOk<TEndpoints, TEndpoint, TMethod>,
|
|
159
159
|
EndpointResponseFail<TEndpoints, TEndpoint, TMethod>
|
|
@@ -240,7 +240,7 @@ declare namespace Koine.Api {
|
|
|
240
240
|
TEndpoint extends EndpointUrl<TEndpoints>,
|
|
241
241
|
TMethod extends RequestMethod,
|
|
242
242
|
TJson extends RequestJson,
|
|
243
|
-
TQuery extends RequestQuery
|
|
243
|
+
TQuery extends RequestQuery,
|
|
244
244
|
> = Omit<ClientOptions, "processReq"> & {
|
|
245
245
|
processReq?: EndpointRequestProcessor<TEndpoints, TEndpoint, TMethod>;
|
|
246
246
|
/**
|
|
@@ -273,7 +273,7 @@ declare namespace Koine.Api {
|
|
|
273
273
|
type ResponseFail = unknown;
|
|
274
274
|
|
|
275
275
|
type ResultShared<
|
|
276
|
-
T extends Record<string, unknown> = Record<string, unknown
|
|
276
|
+
T extends Record<string, unknown> = Record<string, unknown>,
|
|
277
277
|
> = T & {
|
|
278
278
|
status: _Response["status"];
|
|
279
279
|
msg: _Response["statusText"];
|
|
@@ -297,7 +297,7 @@ declare namespace Koine.Api {
|
|
|
297
297
|
|
|
298
298
|
type Result<
|
|
299
299
|
TResponseOk extends ResponseOk,
|
|
300
|
-
TResponseFail extends ResponseFail
|
|
300
|
+
TResponseFail extends ResponseFail,
|
|
301
301
|
> =
|
|
302
302
|
| {
|
|
303
303
|
status: _Response["status"];
|
|
@@ -324,13 +324,13 @@ declare namespace Koine.Api {
|
|
|
324
324
|
query: any,
|
|
325
325
|
json: any,
|
|
326
326
|
params: any,
|
|
327
|
-
requestInit: RequestInit
|
|
327
|
+
requestInit: RequestInit,
|
|
328
328
|
) => [
|
|
329
329
|
string, // url
|
|
330
330
|
RequestQuery, // query
|
|
331
331
|
RequestJson, // json
|
|
332
332
|
RequestParams, // params
|
|
333
|
-
RequestInit // requestInit
|
|
333
|
+
RequestInit, // requestInit
|
|
334
334
|
];
|
|
335
335
|
|
|
336
336
|
/**
|
|
@@ -343,20 +343,20 @@ declare namespace Koine.Api {
|
|
|
343
343
|
type EndpointRequestProcessor<
|
|
344
344
|
TEndpoints extends Endpoints,
|
|
345
345
|
TEndpoint extends EndpointUrl<TEndpoints>,
|
|
346
|
-
TMethod extends RequestMethod
|
|
346
|
+
TMethod extends RequestMethod,
|
|
347
347
|
> = (
|
|
348
348
|
method: TMethod,
|
|
349
349
|
url: string,
|
|
350
350
|
query: EndpointOptions<TEndpoints, TEndpoint, TMethod>["query"],
|
|
351
351
|
json: EndpointOptions<TEndpoints, TEndpoint, TMethod>["json"],
|
|
352
352
|
params: EndpointOptions<TEndpoints, TEndpoint, TMethod>["params"],
|
|
353
|
-
requestInit: RequestInit
|
|
353
|
+
requestInit: RequestInit,
|
|
354
354
|
) => [
|
|
355
355
|
string, // url
|
|
356
356
|
EndpointOptions<TEndpoints, TEndpoint, TMethod>["query"], // query
|
|
357
357
|
EndpointOptions<TEndpoints, TEndpoint, TMethod>["json"], // json
|
|
358
358
|
EndpointOptions<TEndpoints, TEndpoint, TMethod>["params"], // params
|
|
359
|
-
RequestInit // requestInit
|
|
359
|
+
RequestInit, // requestInit
|
|
360
360
|
];
|
|
361
361
|
|
|
362
362
|
/**
|
|
@@ -365,7 +365,7 @@ declare namespace Koine.Api {
|
|
|
365
365
|
*/
|
|
366
366
|
type ResponseProcessorRes = <TResponseOk extends ResponseOk = ResponseOk>(
|
|
367
367
|
response: _Response,
|
|
368
|
-
options: TOptions
|
|
368
|
+
options: TOptions,
|
|
369
369
|
) => Promise<Koine.Api.Result<TResponseOk>>;
|
|
370
370
|
|
|
371
371
|
/**
|
|
@@ -373,10 +373,10 @@ declare namespace Koine.Api {
|
|
|
373
373
|
* transformations to a single or all endpoint responses
|
|
374
374
|
*/
|
|
375
375
|
type ResponseProcessorErr = <
|
|
376
|
-
TResponseFail extends ResponseFailed = ResponseFailed
|
|
376
|
+
TResponseFail extends ResponseFailed = ResponseFailed,
|
|
377
377
|
>(
|
|
378
378
|
msg: string,
|
|
379
|
-
options: TOptions
|
|
379
|
+
options: TOptions,
|
|
380
380
|
) => Promise<Koine.Api.Result<TResponseFail>>;
|
|
381
381
|
|
|
382
382
|
//////////////////////////////////////////////////////////////////////////////
|
|
@@ -393,7 +393,7 @@ declare namespace Koine.Api {
|
|
|
393
393
|
* standalone hooks, see SWR ones to start with.
|
|
394
394
|
*/
|
|
395
395
|
type HooksMaps = {
|
|
396
|
-
[TMethod in RequestMethod]: `use${Capitalize<TMethod>}`;
|
|
396
|
+
[TMethod in RequestMethod]: `use${TMethod extends "get" ? "" : Capitalize<TMethod>}`;
|
|
397
397
|
};
|
|
398
398
|
|
|
399
399
|
type HooksMapsByName = { [K in keyof HooksMaps as HooksMaps[K]]: K };
|
|
@@ -424,6 +424,30 @@ declare namespace Koine.Api {
|
|
|
424
424
|
[K in keyof _ShortcutsMaps as _ShortcutsMaps[K]]: K;
|
|
425
425
|
};
|
|
426
426
|
|
|
427
|
+
/**
|
|
428
|
+
* @example
|
|
429
|
+
* ```ts
|
|
430
|
+
* // define the type on your `API` types:
|
|
431
|
+
* type Result = Koine.Api.GenerateResultShortcuts<Endpoints>;
|
|
432
|
+
*
|
|
433
|
+
* // consume the type wherever in your app:
|
|
434
|
+
* type MyResult = API.Result["get"]["my/endpoint"];
|
|
435
|
+
*
|
|
436
|
+
* MyResult["ok"];
|
|
437
|
+
* ^
|
|
438
|
+
* MyResult["fail"];
|
|
439
|
+
* ^
|
|
440
|
+
* ```
|
|
441
|
+
*/
|
|
442
|
+
type GenerateResultShortcuts<TEndpoints extends Endpoints> = {
|
|
443
|
+
[TMethod in RequestMethod]: {
|
|
444
|
+
[TEndpointUrl in keyof TEndpoints]: {
|
|
445
|
+
ok: TEndpoints[TEndpointUrl][Uppercase<TMethod>]["ok"];
|
|
446
|
+
fail: TEndpoints[TEndpointUrl][Uppercase<TMethod>]["fail"];
|
|
447
|
+
};
|
|
448
|
+
};
|
|
449
|
+
};
|
|
450
|
+
|
|
427
451
|
/**
|
|
428
452
|
* @example
|
|
429
453
|
* ```ts
|
package/ApiError.d.ts
DELETED
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Custom `ApiError` class extending `Error` to throw in failed response.
|
|
3
|
-
*
|
|
4
|
-
* @see https://eslint.org/docs/rules/no-throw-literal
|
|
5
|
-
* @see https://github.com/sindresorhus/ky/blob/main/source/errors/HTTPError.ts
|
|
6
|
-
*
|
|
7
|
-
*/
|
|
8
|
-
export declare class ApiError<TResponseFail extends Koine.Api.ResponseFail = unknown> extends Error {
|
|
9
|
-
constructor(result: Koine.Api.ResultFail<TResponseFail>);
|
|
10
|
-
}
|
|
11
|
-
export default ApiError;
|
package/ApiError.js
DELETED
|
@@ -1,32 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Custom `ApiError` class extending `Error` to throw in failed response.
|
|
3
|
-
*
|
|
4
|
-
* @see https://eslint.org/docs/rules/no-throw-literal
|
|
5
|
-
* @see https://github.com/sindresorhus/ky/blob/main/source/errors/HTTPError.ts
|
|
6
|
-
*
|
|
7
|
-
*/ "use strict";
|
|
8
|
-
Object.defineProperty(exports, "__esModule", {
|
|
9
|
-
value: true
|
|
10
|
-
});
|
|
11
|
-
function _export(target, all) {
|
|
12
|
-
for(var name in all)Object.defineProperty(target, name, {
|
|
13
|
-
enumerable: true,
|
|
14
|
-
get: all[name]
|
|
15
|
-
});
|
|
16
|
-
}
|
|
17
|
-
_export(exports, {
|
|
18
|
-
ApiError: function() {
|
|
19
|
-
return ApiError;
|
|
20
|
-
},
|
|
21
|
-
default: function() {
|
|
22
|
-
return _default;
|
|
23
|
-
}
|
|
24
|
-
});
|
|
25
|
-
let ApiError = class ApiError extends Error {
|
|
26
|
-
constructor(result){
|
|
27
|
-
super(`Request failed with ${result.status} ${result.msg}`);
|
|
28
|
-
this.name = "ApiError";
|
|
29
|
-
Object.assign(this, result);
|
|
30
|
-
}
|
|
31
|
-
};
|
|
32
|
-
const _default = ApiError;
|
package/ApiError.mjs
DELETED
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Custom `ApiError` class extending `Error` to throw in failed response.
|
|
3
|
-
*
|
|
4
|
-
* @see https://eslint.org/docs/rules/no-throw-literal
|
|
5
|
-
* @see https://github.com/sindresorhus/ky/blob/main/source/errors/HTTPError.ts
|
|
6
|
-
*
|
|
7
|
-
*/ export class ApiError extends Error {
|
|
8
|
-
constructor(result){
|
|
9
|
-
super(`Request failed with ${result.status} ${result.msg}`);
|
|
10
|
-
this.name = "ApiError";
|
|
11
|
-
Object.assign(this, result);
|
|
12
|
-
}
|
|
13
|
-
}
|
|
14
|
-
export default ApiError;
|
package/createApi.d.ts
DELETED
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Create api client
|
|
3
|
-
*
|
|
4
|
-
* @param apiName Short name to use in debug logs
|
|
5
|
-
* @param baseUrl Either relativ eor absolute, it must end without trailing slash
|
|
6
|
-
*/
|
|
7
|
-
export declare const createApi: <TEndpoints extends Koine.Api.Endpoints>(apiName: string, baseUrl: string, options?: Koine.Api.ClientOptions) => Koine.Api.Client<TEndpoints>;
|
|
8
|
-
export default createApi;
|
package/createApi.js
DELETED
|
@@ -1,142 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", {
|
|
3
|
-
value: true
|
|
4
|
-
});
|
|
5
|
-
function _export(target, all) {
|
|
6
|
-
for(var name in all)Object.defineProperty(target, name, {
|
|
7
|
-
enumerable: true,
|
|
8
|
-
get: all[name]
|
|
9
|
-
});
|
|
10
|
-
}
|
|
11
|
-
_export(exports, {
|
|
12
|
-
createApi: function() {
|
|
13
|
-
return createApi;
|
|
14
|
-
},
|
|
15
|
-
default: function() {
|
|
16
|
-
return _default;
|
|
17
|
-
}
|
|
18
|
-
});
|
|
19
|
-
const _interop_require_default = require("@swc/helpers/_/_interop_require_default");
|
|
20
|
-
const _buildUrlQueryString = /*#__PURE__*/ _interop_require_default._(require("@koine/utils/buildUrlQueryString"));
|
|
21
|
-
const _errorToString = /*#__PURE__*/ _interop_require_default._(require("@koine/utils/errorToString"));
|
|
22
|
-
const _isFullObject = /*#__PURE__*/ _interop_require_default._(require("@koine/utils/isFullObject"));
|
|
23
|
-
const createApi = (apiName, baseUrl, options)=>{
|
|
24
|
-
const { headers: headersBase = {}, request: requestBase = {
|
|
25
|
-
referrerPolicy: "no-referrer"
|
|
26
|
-
}, throwErr: throwErrBase, timeout: timeoutBase = 10000, processReq: processReqBase, processRes: processResBase, processErr: processErrBase } = options || {};
|
|
27
|
-
return [
|
|
28
|
-
"get",
|
|
29
|
-
"post",
|
|
30
|
-
"put",
|
|
31
|
-
"patch",
|
|
32
|
-
"delete"
|
|
33
|
-
].reduce((api, method)=>{
|
|
34
|
-
// @ts-expect-error FIXME: type
|
|
35
|
-
api[method] = async (endpoint, options)=>{
|
|
36
|
-
const { request = requestBase, headers = headersBase, timeout = timeoutBase, processReq, processRes = processResBase, processErr = processErrBase, throwErr = throwErrBase } = options || {};
|
|
37
|
-
let { params, json, query } = options || {};
|
|
38
|
-
let url = `${baseUrl}/${endpoint + "".replace(/^\/*/, "")}`;
|
|
39
|
-
let requestInit = {
|
|
40
|
-
method: method.toUpperCase(),
|
|
41
|
-
...request,
|
|
42
|
-
headers: {
|
|
43
|
-
"content-type": "application/json",
|
|
44
|
-
...headers
|
|
45
|
-
}
|
|
46
|
-
};
|
|
47
|
-
if (processReqBase) {
|
|
48
|
-
const transformed = processReqBase(method, url, query, json, params, requestInit);
|
|
49
|
-
url = transformed[0];
|
|
50
|
-
query = transformed[1];
|
|
51
|
-
json = transformed[2];
|
|
52
|
-
params = transformed[3];
|
|
53
|
-
requestInit = transformed[4];
|
|
54
|
-
}
|
|
55
|
-
if (processReq) {
|
|
56
|
-
const transformed = processReq(method, url, query, json, params, requestInit);
|
|
57
|
-
url = transformed[0];
|
|
58
|
-
query = transformed[1];
|
|
59
|
-
json = transformed[2];
|
|
60
|
-
params = transformed[3];
|
|
61
|
-
requestInit = transformed[4];
|
|
62
|
-
}
|
|
63
|
-
if ((0, _isFullObject.default)(params)) {
|
|
64
|
-
for(const key in params){
|
|
65
|
-
url = url.replace(`{${key}}`, params[key].toString());
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
const timeoutNumber = Number(timeout);
|
|
69
|
-
let controller;
|
|
70
|
-
let timeoutId;
|
|
71
|
-
if (json) {
|
|
72
|
-
requestInit.body = JSON.stringify(json);
|
|
73
|
-
}
|
|
74
|
-
if (timeoutNumber > 0) {
|
|
75
|
-
controller = new AbortController();
|
|
76
|
-
timeoutId = setTimeout(()=>controller.abort(), timeoutNumber);
|
|
77
|
-
requestInit.signal = controller.signal;
|
|
78
|
-
}
|
|
79
|
-
if (query) {
|
|
80
|
-
// FIXME: ts-expect-error this assertion is not the best, but nevermind for now
|
|
81
|
-
url += (0, _buildUrlQueryString.default)(query);
|
|
82
|
-
}
|
|
83
|
-
let response = null;
|
|
84
|
-
let result = null;
|
|
85
|
-
let msg = "";
|
|
86
|
-
try {
|
|
87
|
-
response = await fetch(url, requestInit);
|
|
88
|
-
} catch (e) {
|
|
89
|
-
msg = (0, _errorToString.default)(e);
|
|
90
|
-
}
|
|
91
|
-
if (timeoutId) {
|
|
92
|
-
clearTimeout(timeoutId);
|
|
93
|
-
}
|
|
94
|
-
if (response) {
|
|
95
|
-
try {
|
|
96
|
-
if (processRes) {
|
|
97
|
-
result = await processRes(response, options || {});
|
|
98
|
-
} else {
|
|
99
|
-
result = await response.json();
|
|
100
|
-
}
|
|
101
|
-
} catch (e) {
|
|
102
|
-
msg = (0, _errorToString.default)(e);
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
if (result === null) {
|
|
106
|
-
if (processErr) {
|
|
107
|
-
result = await processErr(msg, options || {});
|
|
108
|
-
} else {
|
|
109
|
-
// this error should only happen on network errors or wrong API urls
|
|
110
|
-
// there is no specific HTTP error for this, we can consider these
|
|
111
|
-
// two statuses though:
|
|
112
|
-
// - [100 Continue](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/100)
|
|
113
|
-
// - [501 Not Implemented](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/501)
|
|
114
|
-
result = {
|
|
115
|
-
data: null,
|
|
116
|
-
msg,
|
|
117
|
-
status: 100,
|
|
118
|
-
fail: true,
|
|
119
|
-
ok: false
|
|
120
|
-
};
|
|
121
|
-
}
|
|
122
|
-
}
|
|
123
|
-
if (throwErr && result?.fail) {
|
|
124
|
-
// throw new ApiError<Failed>(result);
|
|
125
|
-
// I prefer to throw an object literal despite what eslint says
|
|
126
|
-
// eslint-disable-next-line no-throw-literal
|
|
127
|
-
throw result;
|
|
128
|
-
}
|
|
129
|
-
if (process.env["NODE_ENV"] !== "production") {
|
|
130
|
-
const logMsg = `${result?.status}: api[${apiName}] ${method.toUpperCase()} ${url}`;
|
|
131
|
-
if (result?.ok) {
|
|
132
|
-
console.info(`🟢 ${logMsg}`);
|
|
133
|
-
} else {
|
|
134
|
-
console.info(`🔴 ${logMsg}`);
|
|
135
|
-
}
|
|
136
|
-
}
|
|
137
|
-
return result;
|
|
138
|
-
};
|
|
139
|
-
return api;
|
|
140
|
-
}, {});
|
|
141
|
-
};
|
|
142
|
-
const _default = createApi;
|
package/createApi.mjs
DELETED
|
@@ -1,128 +0,0 @@
|
|
|
1
|
-
import buildUrlQueryString from "@koine/utils/buildUrlQueryString";
|
|
2
|
-
import errorToString from "@koine/utils/errorToString";
|
|
3
|
-
import isFullObject from "@koine/utils/isFullObject";
|
|
4
|
-
/**
|
|
5
|
-
* Create api client
|
|
6
|
-
*
|
|
7
|
-
* @param apiName Short name to use in debug logs
|
|
8
|
-
* @param baseUrl Either relativ eor absolute, it must end without trailing slash
|
|
9
|
-
*/ export const createApi = (apiName, baseUrl, options)=>{
|
|
10
|
-
const { headers: headersBase = {}, request: requestBase = {
|
|
11
|
-
referrerPolicy: "no-referrer"
|
|
12
|
-
}, throwErr: throwErrBase, timeout: timeoutBase = 10000, processReq: processReqBase, processRes: processResBase, processErr: processErrBase } = options || {};
|
|
13
|
-
return [
|
|
14
|
-
"get",
|
|
15
|
-
"post",
|
|
16
|
-
"put",
|
|
17
|
-
"patch",
|
|
18
|
-
"delete"
|
|
19
|
-
].reduce((api, method)=>{
|
|
20
|
-
// @ts-expect-error FIXME: type
|
|
21
|
-
api[method] = async (endpoint, options)=>{
|
|
22
|
-
const { request = requestBase, headers = headersBase, timeout = timeoutBase, processReq, processRes = processResBase, processErr = processErrBase, throwErr = throwErrBase } = options || {};
|
|
23
|
-
let { params, json, query } = options || {};
|
|
24
|
-
let url = `${baseUrl}/${endpoint + "".replace(/^\/*/, "")}`;
|
|
25
|
-
let requestInit = {
|
|
26
|
-
method: method.toUpperCase(),
|
|
27
|
-
...request,
|
|
28
|
-
headers: {
|
|
29
|
-
"content-type": "application/json",
|
|
30
|
-
...headers
|
|
31
|
-
}
|
|
32
|
-
};
|
|
33
|
-
if (processReqBase) {
|
|
34
|
-
const transformed = processReqBase(method, url, query, json, params, requestInit);
|
|
35
|
-
url = transformed[0];
|
|
36
|
-
query = transformed[1];
|
|
37
|
-
json = transformed[2];
|
|
38
|
-
params = transformed[3];
|
|
39
|
-
requestInit = transformed[4];
|
|
40
|
-
}
|
|
41
|
-
if (processReq) {
|
|
42
|
-
const transformed = processReq(method, url, query, json, params, requestInit);
|
|
43
|
-
url = transformed[0];
|
|
44
|
-
query = transformed[1];
|
|
45
|
-
json = transformed[2];
|
|
46
|
-
params = transformed[3];
|
|
47
|
-
requestInit = transformed[4];
|
|
48
|
-
}
|
|
49
|
-
if (isFullObject(params)) {
|
|
50
|
-
for(const key in params){
|
|
51
|
-
url = url.replace(`{${key}}`, params[key].toString());
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
const timeoutNumber = Number(timeout);
|
|
55
|
-
let controller;
|
|
56
|
-
let timeoutId;
|
|
57
|
-
if (json) {
|
|
58
|
-
requestInit.body = JSON.stringify(json);
|
|
59
|
-
}
|
|
60
|
-
if (timeoutNumber > 0) {
|
|
61
|
-
controller = new AbortController();
|
|
62
|
-
timeoutId = setTimeout(()=>controller.abort(), timeoutNumber);
|
|
63
|
-
requestInit.signal = controller.signal;
|
|
64
|
-
}
|
|
65
|
-
if (query) {
|
|
66
|
-
// FIXME: ts-expect-error this assertion is not the best, but nevermind for now
|
|
67
|
-
url += buildUrlQueryString(query);
|
|
68
|
-
}
|
|
69
|
-
let response = null;
|
|
70
|
-
let result = null;
|
|
71
|
-
let msg = "";
|
|
72
|
-
try {
|
|
73
|
-
response = await fetch(url, requestInit);
|
|
74
|
-
} catch (e) {
|
|
75
|
-
msg = errorToString(e);
|
|
76
|
-
}
|
|
77
|
-
if (timeoutId) {
|
|
78
|
-
clearTimeout(timeoutId);
|
|
79
|
-
}
|
|
80
|
-
if (response) {
|
|
81
|
-
try {
|
|
82
|
-
if (processRes) {
|
|
83
|
-
result = await processRes(response, options || {});
|
|
84
|
-
} else {
|
|
85
|
-
result = await response.json();
|
|
86
|
-
}
|
|
87
|
-
} catch (e) {
|
|
88
|
-
msg = errorToString(e);
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
if (result === null) {
|
|
92
|
-
if (processErr) {
|
|
93
|
-
result = await processErr(msg, options || {});
|
|
94
|
-
} else {
|
|
95
|
-
// this error should only happen on network errors or wrong API urls
|
|
96
|
-
// there is no specific HTTP error for this, we can consider these
|
|
97
|
-
// two statuses though:
|
|
98
|
-
// - [100 Continue](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/100)
|
|
99
|
-
// - [501 Not Implemented](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/501)
|
|
100
|
-
result = {
|
|
101
|
-
data: null,
|
|
102
|
-
msg,
|
|
103
|
-
status: 100,
|
|
104
|
-
fail: true,
|
|
105
|
-
ok: false
|
|
106
|
-
};
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
if (throwErr && result?.fail) {
|
|
110
|
-
// throw new ApiError<Failed>(result);
|
|
111
|
-
// I prefer to throw an object literal despite what eslint says
|
|
112
|
-
// eslint-disable-next-line no-throw-literal
|
|
113
|
-
throw result;
|
|
114
|
-
}
|
|
115
|
-
if (process.env["NODE_ENV"] !== "production") {
|
|
116
|
-
const logMsg = `${result?.status}: api[${apiName}] ${method.toUpperCase()} ${url}`;
|
|
117
|
-
if (result?.ok) {
|
|
118
|
-
console.info(`🟢 ${logMsg}`);
|
|
119
|
-
} else {
|
|
120
|
-
console.info(`🔴 ${logMsg}`);
|
|
121
|
-
}
|
|
122
|
-
}
|
|
123
|
-
return result;
|
|
124
|
-
};
|
|
125
|
-
return api;
|
|
126
|
-
}, {});
|
|
127
|
-
};
|
|
128
|
-
export default createApi;
|
package/createSwrApi.d.ts
DELETED
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
import { type BareFetcher, // type Fetcher,
|
|
2
|
-
type SWRConfiguration, type SWRResponse } from "swr";
|
|
3
|
-
import { type SWRMutationConfiguration, type SWRMutationResponse } from "swr/mutation";
|
|
4
|
-
type SWRConfigurationExtended<Data = any, Error = any, Fn extends BareFetcher<any> = BareFetcher<any>> = SWRConfiguration<Data, Error, Fn> & {
|
|
5
|
-
/**
|
|
6
|
-
* Conditional fetching as option
|
|
7
|
-
*
|
|
8
|
-
* Moving this to an option allows us to keep the endpoints typed dictionary,
|
|
9
|
-
* e.g. we can write:
|
|
10
|
-
*
|
|
11
|
-
* ```js
|
|
12
|
-
* const { data, mutate } = myApi.useGet("User/{id}",
|
|
13
|
-
* { params: { id: aVariableMaybeContainingAnId || "" }, },
|
|
14
|
-
* { when: !!aVariableMaybeContainingAnId }
|
|
15
|
-
* );
|
|
16
|
-
*
|
|
17
|
-
* // we still have typed `data`, `mutate`
|
|
18
|
-
* ```
|
|
19
|
-
* @see https://swr.vercel.app/docs/conditional-fetching
|
|
20
|
-
*/
|
|
21
|
-
when?: boolean | (() => boolean);
|
|
22
|
-
};
|
|
23
|
-
type KoineApiMethodHookSWR<THookName extends keyof Koine.Api.HooksMapsByName, TEndpoints extends Koine.Api.Endpoints> = <TEndpoint extends Koine.Api.EndpointUrl<TEndpoints>, TMethod extends Koine.Api.RequestMethod = Koine.Api.HooksMapsByName[THookName]>(endpoint: TEndpoint, options?: Koine.Api.EndpointOptions<TEndpoints, TEndpoint, TMethod>, config?: THookName extends "useGet" ? SWRConfigurationExtended<Koine.Api.EndpointResponseOk<TEndpoints, TEndpoint, TMethod>, Koine.Api.EndpointResponseFail<TEndpoints, TEndpoint, TMethod>> : SWRMutationConfiguration<Koine.Api.EndpointResponseOk<TEndpoints, TEndpoint, TMethod>, Koine.Api.EndpointResponseFail<TEndpoints, TEndpoint, TMethod>, Koine.Api.EndpointOptions<TEndpoints, TEndpoint, TMethod>, TEndpoint>) => THookName extends "useGet" ? SWRResponse<Koine.Api.EndpointResponseOk<TEndpoints, TEndpoint, TMethod>, Koine.Api.EndpointResponseFail<TEndpoints, TEndpoint, TMethod>> : SWRMutationResponse<Koine.Api.EndpointResponseOk<TEndpoints, TEndpoint, TMethod>, Koine.Api.EndpointResponseFail<TEndpoints, TEndpoint, TMethod>, Koine.Api.EndpointOptions<TEndpoints, TEndpoint, TMethod>, TEndpoint>;
|
|
24
|
-
/**
|
|
25
|
-
* It creates an api client extended with auto-generated SWR wrapper hooks
|
|
26
|
-
*/
|
|
27
|
-
export declare const createSwrApi: <TEndpoints extends Koine.Api.Endpoints>(apiName: string, baseUrl: string, options?: Koine.Api.ClientOptions | undefined) => Koine.Api.Client<TEndpoints> & {
|
|
28
|
-
useGet: KoineApiMethodHookSWR<"useGet", TEndpoints>;
|
|
29
|
-
usePost: KoineApiMethodHookSWR<"usePost", TEndpoints>;
|
|
30
|
-
usePut: KoineApiMethodHookSWR<"usePut", TEndpoints>;
|
|
31
|
-
usePatch: KoineApiMethodHookSWR<"usePatch", TEndpoints>;
|
|
32
|
-
useDelete: KoineApiMethodHookSWR<"useDelete", TEndpoints>;
|
|
33
|
-
};
|
|
34
|
-
export default createSwrApi;
|
package/createSwrApi.js
DELETED
|
@@ -1,99 +0,0 @@
|
|
|
1
|
-
"use client";
|
|
2
|
-
"use strict";
|
|
3
|
-
Object.defineProperty(exports, "__esModule", {
|
|
4
|
-
value: true
|
|
5
|
-
});
|
|
6
|
-
function _export(target, all) {
|
|
7
|
-
for(var name in all)Object.defineProperty(target, name, {
|
|
8
|
-
enumerable: true,
|
|
9
|
-
get: all[name]
|
|
10
|
-
});
|
|
11
|
-
}
|
|
12
|
-
_export(exports, {
|
|
13
|
-
createSwrApi: function() {
|
|
14
|
-
return createSwrApi;
|
|
15
|
-
},
|
|
16
|
-
default: function() {
|
|
17
|
-
return _default;
|
|
18
|
-
}
|
|
19
|
-
});
|
|
20
|
-
const _interop_require_default = require("@swc/helpers/_/_interop_require_default");
|
|
21
|
-
const _swr = /*#__PURE__*/ _interop_require_default._(require("swr"));
|
|
22
|
-
const _mutation = /*#__PURE__*/ _interop_require_default._(require("swr/mutation"));
|
|
23
|
-
const _isFunction = /*#__PURE__*/ _interop_require_default._(require("@koine/utils/isFunction"));
|
|
24
|
-
const _createApi = /*#__PURE__*/ _interop_require_default._(require("./createApi"));
|
|
25
|
-
function createUseApi(api, method) {
|
|
26
|
-
return function useApi(endpoint, options, _config) {
|
|
27
|
-
if (method === "get") {
|
|
28
|
-
// const fetcher = async (_endpoint: TEndpoint) => {
|
|
29
|
-
// try {
|
|
30
|
-
// const { ok, data } = await api[method](_endpoint, {
|
|
31
|
-
// ...(options || {}),
|
|
32
|
-
// throwErr: true,
|
|
33
|
-
// });
|
|
34
|
-
// if (ok) {
|
|
35
|
-
// return data;
|
|
36
|
-
// }
|
|
37
|
-
// throw new Error() as unknown as Koine.Api.EndpointResponseFail<TEndpoints, TEndpoint, TMethod>;
|
|
38
|
-
// } catch(e) {
|
|
39
|
-
// throw new Error() as unknown as Koine.Api.EndpointResponseFail<TEndpoints, TEndpoint, TMethod>;;
|
|
40
|
-
// }
|
|
41
|
-
// };
|
|
42
|
-
// }
|
|
43
|
-
const fetcher = async ()=>{
|
|
44
|
-
const { data } = await api[method](endpoint, {
|
|
45
|
-
...options || {},
|
|
46
|
-
throwErr: true
|
|
47
|
-
});
|
|
48
|
-
return data;
|
|
49
|
-
};
|
|
50
|
-
const config = _config;
|
|
51
|
-
const shouldNotFetch = config?.when === false || (0, _isFunction.default)(config?.when) && config?.when() === false;
|
|
52
|
-
// <Data = any, Error = any>(key: Key, config: SWRConfigurationExtended<Data, Error, Fetcher<Data>> | undefined): SWRResponse<Data, Error>;
|
|
53
|
-
// eslint-disable-next-line react-hooks/rules-of-hooks
|
|
54
|
-
return (0, _swr.default)(shouldNotFetch ? null : options ? [
|
|
55
|
-
endpoint,
|
|
56
|
-
options
|
|
57
|
-
] : [
|
|
58
|
-
endpoint
|
|
59
|
-
], fetcher, config);
|
|
60
|
-
}
|
|
61
|
-
const config = _config;
|
|
62
|
-
const sender = async (// if the first argument is an array the second tem are the base options
|
|
63
|
-
// defined when calling the usePost/Put/etc. hook, these will be overriden
|
|
64
|
-
// by the _options just here below
|
|
65
|
-
_endpoint, // these are the options arriving when calling `trigger({ json, query, etc... })
|
|
66
|
-
_options)=>{
|
|
67
|
-
const endpoint = Array.isArray(_endpoint) ? _endpoint[0] : _endpoint;
|
|
68
|
-
const options = Array.isArray(_endpoint) ? _endpoint[1] : {};
|
|
69
|
-
const { ok, data } = await api[method](endpoint, {
|
|
70
|
-
...options,
|
|
71
|
-
..._options.arg || {},
|
|
72
|
-
throwErr: true
|
|
73
|
-
});
|
|
74
|
-
return ok ? data : data;
|
|
75
|
-
};
|
|
76
|
-
// config.fetcher = sender;
|
|
77
|
-
// eslint-disable-next-line react-hooks/rules-of-hooks
|
|
78
|
-
return (0, _mutation.default)(// @ts-expect-error FIXME: I can't get it...
|
|
79
|
-
options ? [
|
|
80
|
-
endpoint,
|
|
81
|
-
options
|
|
82
|
-
] : endpoint, sender, config);
|
|
83
|
-
};
|
|
84
|
-
}
|
|
85
|
-
const createSwrApi = (...args)=>{
|
|
86
|
-
const api = (0, _createApi.default)(...args);
|
|
87
|
-
[
|
|
88
|
-
"get",
|
|
89
|
-
"post",
|
|
90
|
-
"put",
|
|
91
|
-
"patch",
|
|
92
|
-
"delete"
|
|
93
|
-
].forEach((method)=>{
|
|
94
|
-
const hookName = `use${method.charAt(0).toUpperCase() + method.slice(1)}`;
|
|
95
|
-
api[hookName] = createUseApi(api, method);
|
|
96
|
-
});
|
|
97
|
-
return api;
|
|
98
|
-
};
|
|
99
|
-
const _default = createSwrApi;
|
package/createSwrApi.mjs
DELETED
|
@@ -1,82 +0,0 @@
|
|
|
1
|
-
"use client";
|
|
2
|
-
import useSWR from "swr";
|
|
3
|
-
import useSWRMutation from "swr/mutation";
|
|
4
|
-
import isFunction from "@koine/utils/isFunction";
|
|
5
|
-
import createApi from "./createApi";
|
|
6
|
-
function createUseApi(api, method) {
|
|
7
|
-
return function useApi(endpoint, options, _config) {
|
|
8
|
-
if (method === "get") {
|
|
9
|
-
// const fetcher = async (_endpoint: TEndpoint) => {
|
|
10
|
-
// try {
|
|
11
|
-
// const { ok, data } = await api[method](_endpoint, {
|
|
12
|
-
// ...(options || {}),
|
|
13
|
-
// throwErr: true,
|
|
14
|
-
// });
|
|
15
|
-
// if (ok) {
|
|
16
|
-
// return data;
|
|
17
|
-
// }
|
|
18
|
-
// throw new Error() as unknown as Koine.Api.EndpointResponseFail<TEndpoints, TEndpoint, TMethod>;
|
|
19
|
-
// } catch(e) {
|
|
20
|
-
// throw new Error() as unknown as Koine.Api.EndpointResponseFail<TEndpoints, TEndpoint, TMethod>;;
|
|
21
|
-
// }
|
|
22
|
-
// };
|
|
23
|
-
// }
|
|
24
|
-
const fetcher = async ()=>{
|
|
25
|
-
const { data } = await api[method](endpoint, {
|
|
26
|
-
...options || {},
|
|
27
|
-
throwErr: true
|
|
28
|
-
});
|
|
29
|
-
return data;
|
|
30
|
-
};
|
|
31
|
-
const config = _config;
|
|
32
|
-
const shouldNotFetch = config?.when === false || isFunction(config?.when) && config?.when() === false;
|
|
33
|
-
// <Data = any, Error = any>(key: Key, config: SWRConfigurationExtended<Data, Error, Fetcher<Data>> | undefined): SWRResponse<Data, Error>;
|
|
34
|
-
// eslint-disable-next-line react-hooks/rules-of-hooks
|
|
35
|
-
return useSWR(shouldNotFetch ? null : options ? [
|
|
36
|
-
endpoint,
|
|
37
|
-
options
|
|
38
|
-
] : [
|
|
39
|
-
endpoint
|
|
40
|
-
], fetcher, config);
|
|
41
|
-
}
|
|
42
|
-
const config = _config;
|
|
43
|
-
const sender = async (// if the first argument is an array the second tem are the base options
|
|
44
|
-
// defined when calling the usePost/Put/etc. hook, these will be overriden
|
|
45
|
-
// by the _options just here below
|
|
46
|
-
_endpoint, // these are the options arriving when calling `trigger({ json, query, etc... })
|
|
47
|
-
_options)=>{
|
|
48
|
-
const endpoint = Array.isArray(_endpoint) ? _endpoint[0] : _endpoint;
|
|
49
|
-
const options = Array.isArray(_endpoint) ? _endpoint[1] : {};
|
|
50
|
-
const { ok, data } = await api[method](endpoint, {
|
|
51
|
-
...options,
|
|
52
|
-
..._options.arg || {},
|
|
53
|
-
throwErr: true
|
|
54
|
-
});
|
|
55
|
-
return ok ? data : data;
|
|
56
|
-
};
|
|
57
|
-
// config.fetcher = sender;
|
|
58
|
-
// eslint-disable-next-line react-hooks/rules-of-hooks
|
|
59
|
-
return useSWRMutation(// @ts-expect-error FIXME: I can't get it...
|
|
60
|
-
options ? [
|
|
61
|
-
endpoint,
|
|
62
|
-
options
|
|
63
|
-
] : endpoint, sender, config);
|
|
64
|
-
};
|
|
65
|
-
}
|
|
66
|
-
/**
|
|
67
|
-
* It creates an api client extended with auto-generated SWR wrapper hooks
|
|
68
|
-
*/ export const createSwrApi = (...args)=>{
|
|
69
|
-
const api = createApi(...args);
|
|
70
|
-
[
|
|
71
|
-
"get",
|
|
72
|
-
"post",
|
|
73
|
-
"put",
|
|
74
|
-
"patch",
|
|
75
|
-
"delete"
|
|
76
|
-
].forEach((method)=>{
|
|
77
|
-
const hookName = `use${method.charAt(0).toUpperCase() + method.slice(1)}`;
|
|
78
|
-
api[hookName] = createUseApi(api, method);
|
|
79
|
-
});
|
|
80
|
-
return api;
|
|
81
|
-
};
|
|
82
|
-
export default createSwrApi;
|
package/index.js
DELETED
|
@@ -1,28 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", {
|
|
3
|
-
value: true
|
|
4
|
-
});
|
|
5
|
-
function _export(target, all) {
|
|
6
|
-
for(var name in all)Object.defineProperty(target, name, {
|
|
7
|
-
enumerable: true,
|
|
8
|
-
get: all[name]
|
|
9
|
-
});
|
|
10
|
-
}
|
|
11
|
-
_export(exports, {
|
|
12
|
-
ApiError: function() {
|
|
13
|
-
return _ApiError.ApiError;
|
|
14
|
-
},
|
|
15
|
-
createApi: function() {
|
|
16
|
-
return _createApi.createApi;
|
|
17
|
-
},
|
|
18
|
-
createSwrApi: function() {
|
|
19
|
-
return _createSwrApi.createSwrApi;
|
|
20
|
-
},
|
|
21
|
-
nextApiResponse: function() {
|
|
22
|
-
return _nextApiResponse.nextApiResponse;
|
|
23
|
-
}
|
|
24
|
-
});
|
|
25
|
-
const _ApiError = require("./ApiError");
|
|
26
|
-
const _createApi = require("./createApi");
|
|
27
|
-
const _createSwrApi = require("./createSwrApi");
|
|
28
|
-
const _nextApiResponse = require("./nextApiResponse");
|
package/index.mjs
DELETED
package/nextApiResponse.d.ts
DELETED
package/nextApiResponse.js
DELETED
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", {
|
|
3
|
-
value: true
|
|
4
|
-
});
|
|
5
|
-
function _export(target, all) {
|
|
6
|
-
for(var name in all)Object.defineProperty(target, name, {
|
|
7
|
-
enumerable: true,
|
|
8
|
-
get: all[name]
|
|
9
|
-
});
|
|
10
|
-
}
|
|
11
|
-
_export(exports, {
|
|
12
|
-
nextApiResponse: function() {
|
|
13
|
-
return nextApiResponse;
|
|
14
|
-
},
|
|
15
|
-
default: function() {
|
|
16
|
-
return _default;
|
|
17
|
-
}
|
|
18
|
-
});
|
|
19
|
-
const nextApiResponse = (nextRes, result)=>{
|
|
20
|
-
// nextRes.status(result.status).json(result.data || result.msg);
|
|
21
|
-
nextRes.status(result.status).json(result);
|
|
22
|
-
};
|
|
23
|
-
const _default = nextApiResponse;
|