@koine/api 2.0.0-beta.2 → 2.0.0-beta.21

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.
@@ -0,0 +1,11 @@
1
+ export var createApiResultOk = function (data, msg) {
2
+ if (data === void 0) { data = {}; }
3
+ return ({
4
+ ok: true,
5
+ fail: false,
6
+ data: data,
7
+ msg: msg || "",
8
+ status: 200,
9
+ });
10
+ };
11
+ export default createApiResultOk;
package/createSwrApi.d.ts CHANGED
@@ -1,28 +1,10 @@
1
- import { type SWRConfiguration, type SWRResponse, type BareFetcher } from "swr";
1
+ /// <reference types="./typings.d.ts" />
2
+ import { type BareFetcher, type SWRConfiguration, type SWRResponse } from "swr";
2
3
  import { type SWRMutationConfiguration, type SWRMutationResponse } from "swr/mutation";
3
4
  type SWRConfigurationExtended<Data = any, Error = any, Fn extends BareFetcher<any> = BareFetcher<any>> = SWRConfiguration<Data, Error, Fn> & {
4
- /**
5
- * Conditional fetching as option
6
- *
7
- * Moving this to an option allows us to keep the endpoints typed dictionary,
8
- * e.g. we can write:
9
- *
10
- * ```js
11
- * const { data, mutate } = myApi.useGet("User/{id}",
12
- * { params: { id: aVariableMaybeContainingAnId || "" }, },
13
- * { when: !!aVariableMaybeContainingAnId }
14
- * );
15
- *
16
- * // we still have typed `data`, `mutate`
17
- * ```
18
- * @see https://swr.vercel.app/docs/conditional-fetching
19
- */
20
5
  when?: boolean | (() => boolean);
21
6
  };
22
7
  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>;
23
- /**
24
- * It creates an api client extended with auto-generated SWR wrapper hooks
25
- */
26
8
  export declare const createSwrApi: <TEndpoints extends Koine.Api.Endpoints>(apiName: string, baseUrl: string, options?: Koine.Api.ClientOptions | undefined) => Koine.Api.Client<TEndpoints> & {
27
9
  useGet: KoineApiMethodHookSWR<"useGet", TEndpoints>;
28
10
  usePost: KoineApiMethodHookSWR<"usePost", TEndpoints>;
package/createSwrApi.js CHANGED
@@ -1,91 +1,57 @@
1
- "use strict";
2
1
  "use client";
3
- Object.defineProperty(exports, "__esModule", { value: true });
4
- exports.createSwrApi = void 0;
5
- var tslib_1 = require("tslib");
6
- var isFunction_1 = require("@koine/utils/isFunction");
7
- var swr_1 = require("swr");
8
- var mutation_1 = require("swr/mutation");
9
- var createApi_1 = require("./createApi");
2
+ import { __assign, __awaiter, __generator, __read, __spreadArray } from "tslib";
3
+ import useSWR from "swr";
4
+ import useSWRMutation from "swr/mutation";
5
+ import { isFunction } from "@koine/utils";
6
+ import createApi from "./createApi.js";
10
7
  function createUseApi(api, method) {
11
8
  return function useApi(endpoint, options, _config) {
12
9
  var _this = this;
13
10
  if (method === "get") {
14
- // const fetcher = async (_endpoint: TEndpoint) => {
15
- // try {
16
- // const { ok, data } = await api[method](_endpoint, {
17
- // ...(options || {}),
18
- // throwErr: true,
19
- // });
20
- // if (ok) {
21
- // return data;
22
- // }
23
- // throw new Error() as unknown as Koine.Api.EndpointResponseFail<TEndpoints, TEndpoint, TMethod>;
24
- // } catch(e) {
25
- // throw new Error() as unknown as Koine.Api.EndpointResponseFail<TEndpoints, TEndpoint, TMethod>;;
26
- // }
27
- // };
28
- // }
29
- var fetcher = function () { return tslib_1.__awaiter(_this, void 0, void 0, function () {
11
+ var fetcher = function () { return __awaiter(_this, void 0, void 0, function () {
30
12
  var data;
31
- return tslib_1.__generator(this, function (_a) {
13
+ return __generator(this, function (_a) {
32
14
  switch (_a.label) {
33
- case 0: return [4 /*yield*/, api[method](endpoint, tslib_1.__assign(tslib_1.__assign({}, (options || {})), { throwErr: true }))];
15
+ case 0: return [4, api[method](endpoint, __assign(__assign({}, (options || {})), { throwErr: true }))];
34
16
  case 1:
35
17
  data = (_a.sent()).data;
36
- return [2 /*return*/, data];
18
+ return [2, data];
37
19
  }
38
20
  });
39
21
  }); };
40
22
  var config_1 = _config;
41
23
  var shouldNotFetch = (config_1 === null || config_1 === void 0 ? void 0 : config_1.when) === false ||
42
- ((0, isFunction_1.default)(config_1 === null || config_1 === void 0 ? void 0 : config_1.when) && (config_1 === null || config_1 === void 0 ? void 0 : config_1.when()) === false);
43
- // <Data = any, Error = any>(key: Key, config: SWRConfigurationExtended<Data, Error, Fetcher<Data>> | undefined): SWRResponse<Data, Error>;
44
- // eslint-disable-next-line react-hooks/rules-of-hooks
45
- return (0, swr_1.default)(shouldNotFetch ? null : options ? [endpoint, options] : [endpoint], fetcher, config_1);
24
+ (isFunction(config_1 === null || config_1 === void 0 ? void 0 : config_1.when) && (config_1 === null || config_1 === void 0 ? void 0 : config_1.when()) === false);
25
+ return useSWR(shouldNotFetch ? null : options ? [endpoint, options] : [endpoint], fetcher, config_1);
46
26
  }
47
27
  var config = _config;
48
- var sender = function (
49
- // if the first argument is an array the second tem are the base options
50
- // defined when calling the usePost/Put/etc. hook, these will be overriden
51
- // by the _options just here below
52
- _endpoint,
53
- // these are the options arriving when calling `trigger({ json, query, etc... })
54
- _options) { return tslib_1.__awaiter(_this, void 0, void 0, function () {
28
+ var sender = function (_endpoint, _options) { return __awaiter(_this, void 0, void 0, function () {
55
29
  var endpoint, options, _a, ok, data;
56
- return tslib_1.__generator(this, function (_b) {
30
+ return __generator(this, function (_b) {
57
31
  switch (_b.label) {
58
32
  case 0:
59
33
  endpoint = Array.isArray(_endpoint) ? _endpoint[0] : _endpoint;
60
34
  options = Array.isArray(_endpoint) ? _endpoint[1] : {};
61
- return [4 /*yield*/, api[method](endpoint, tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({}, options), (_options.arg || {})), { throwErr: true }))];
35
+ return [4, api[method](endpoint, __assign(__assign(__assign({}, options), (_options.arg || {})), { throwErr: true }))];
62
36
  case 1:
63
37
  _a = _b.sent(), ok = _a.ok, data = _a.data;
64
- return [2 /*return*/, ok ? data : data];
38
+ return [2, ok ? data : data];
65
39
  }
66
40
  });
67
41
  }); };
68
- // config.fetcher = sender;
69
- // eslint-disable-next-line react-hooks/rules-of-hooks
70
- return (0, mutation_1.default)(
71
- // @ts-expect-error FIXME: I can't get it...
72
- options ? [endpoint, options] : endpoint, sender, config);
42
+ return useSWRMutation(options ? [endpoint, options] : endpoint, sender, config);
73
43
  };
74
44
  }
75
- /**
76
- * It creates an api client extended with auto-generated SWR wrapper hooks
77
- */
78
- var createSwrApi = function () {
45
+ export var createSwrApi = function () {
79
46
  var args = [];
80
47
  for (var _i = 0; _i < arguments.length; _i++) {
81
48
  args[_i] = arguments[_i];
82
49
  }
83
- var api = createApi_1.default.apply(void 0, args);
50
+ var api = createApi.apply(void 0, __spreadArray([], __read(args), false));
84
51
  ["get", "post", "put", "patch", "delete"].forEach(function (method) {
85
52
  var hookName = "use".concat(method.charAt(0).toUpperCase() + method.slice(1));
86
53
  api[hookName] = createUseApi(api, method);
87
54
  });
88
55
  return api;
89
56
  };
90
- exports.createSwrApi = createSwrApi;
91
- exports.default = exports.createSwrApi;
57
+ export default createSwrApi;
package/index.d.ts CHANGED
@@ -1,4 +1,6 @@
1
- export { ApiError } from "./ApiError";
2
- export { createApi } from "./createApi";
3
- export { createSwrApi } from "./createSwrApi";
4
- export { nextApiResponse } from "./nextApiResponse";
1
+ export { ApiError } from "./ApiError.js";
2
+ export { createApi } from "./createApi.js";
3
+ export { createApiResultFail } from "./createApiResultFail.js";
4
+ export { createApiResultOk } from "./createApiResultOk.js";
5
+ export { createSwrApi } from "./createSwrApi.js";
6
+ export { nextApiResponse12 } from "./nextApiResponse12.js";
package/index.js CHANGED
@@ -1,11 +1,6 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.nextApiResponse = exports.createSwrApi = exports.createApi = exports.ApiError = void 0;
4
- var ApiError_1 = require("./ApiError");
5
- Object.defineProperty(exports, "ApiError", { enumerable: true, get: function () { return ApiError_1.ApiError; } });
6
- var createApi_1 = require("./createApi");
7
- Object.defineProperty(exports, "createApi", { enumerable: true, get: function () { return createApi_1.createApi; } });
8
- var createSwrApi_1 = require("./createSwrApi");
9
- Object.defineProperty(exports, "createSwrApi", { enumerable: true, get: function () { return createSwrApi_1.createSwrApi; } });
10
- var nextApiResponse_1 = require("./nextApiResponse");
11
- Object.defineProperty(exports, "nextApiResponse", { enumerable: true, get: function () { return nextApiResponse_1.nextApiResponse; } });
1
+ export { ApiError } from "./ApiError.js";
2
+ export { createApi } from "./createApi.js";
3
+ export { createApiResultFail } from "./createApiResultFail.js";
4
+ export { createApiResultOk } from "./createApiResultOk.js";
5
+ export { createSwrApi } from "./createSwrApi.js";
6
+ export { nextApiResponse12 } from "./nextApiResponse12.js";
@@ -1,3 +1,6 @@
1
- import type { NextApiResponse } from "next";
2
- export declare const nextApiResponse: (nextRes: NextApiResponse, result: Koine.Api.ResultOk | Koine.Api.ResultFail) => void;
1
+ import { NextResponse } from "next/server";
2
+ export declare const nextApiResponse: {
3
+ ok<T>(data: T, msg?: string): NextResponse<Koine.Api.ResultOk<T>>;
4
+ fail<T_1>(data: T_1, msg?: string, status?: number): NextResponse<Koine.Api.ResultFail<T_1>>;
5
+ };
3
6
  export default nextApiResponse;
@@ -1,9 +1,12 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.nextApiResponse = void 0;
4
- var nextApiResponse = function (nextRes, result) {
5
- // nextRes.status(result.status).json(result.data || result.msg);
6
- nextRes.status(result.status).json(result);
1
+ import { NextResponse } from "next/server";
2
+ import createApiResultFail from "./createApiResultFail.js";
3
+ import createApiResultOk from "./createApiResultOk.js";
4
+ export var nextApiResponse = {
5
+ ok: function (data, msg) {
6
+ return NextResponse.json(createApiResultOk(data, msg));
7
+ },
8
+ fail: function (data, msg, status) {
9
+ return NextResponse.json(createApiResultFail(data, msg, status));
10
+ },
7
11
  };
8
- exports.nextApiResponse = nextApiResponse;
9
- exports.default = exports.nextApiResponse;
12
+ export default nextApiResponse;
@@ -0,0 +1,6 @@
1
+ import type { NextApiResponse } from "next";
2
+ export declare const nextApiResponse12: (nextRes: NextApiResponse) => {
3
+ ok<T>(data: T, msg?: string): void;
4
+ fail<T_1>(data: T_1, msg?: string, status?: number): void;
5
+ };
6
+ export default nextApiResponse12;
@@ -0,0 +1,15 @@
1
+ import createApiResultFail from "./createApiResultFail.js";
2
+ import createApiResultOk from "./createApiResultOk.js";
3
+ export var nextApiResponse12 = function (nextRes) {
4
+ return {
5
+ ok: function (data, msg) {
6
+ nextRes.status(200).json(createApiResultOk(data, msg));
7
+ },
8
+ fail: function (data, msg, status) {
9
+ nextRes
10
+ .status(status || 404)
11
+ .json(createApiResultFail(data, msg, status));
12
+ },
13
+ };
14
+ };
15
+ export default nextApiResponse12;
package/package.json CHANGED
@@ -1,24 +1,55 @@
1
1
  {
2
2
  "name": "@koine/api",
3
3
  "sideEffects": false,
4
+ "dependencies": {
5
+ "@koine/utils": "2.0.0-beta.21"
6
+ },
4
7
  "peerDependenciesMeta": {
5
8
  "next": {
6
9
  "optional": true
10
+ },
11
+ "swr": {
12
+ "optional": true
7
13
  }
8
14
  },
9
- "dependencies": {
10
- "clsx": "1.2.1",
11
- "next": "^13.4.4",
12
- "swr": "^2.1.5",
13
- "ts-debounce": "^4.0.0",
14
- "type-fest": "^3.11.1"
15
- },
16
- "peerDependencies": {
17
- "@koine/utils": "2.0.0-beta.2",
18
- "tslib": "2.5.3"
19
- },
20
- "main": "./index.js",
15
+ "main": "./cjs/index.js",
21
16
  "types": "./index.d.ts",
22
- "version": "2.0.0-beta.2",
23
- "module": "./index.mjs"
17
+ "type": "module",
18
+ "module": "./index.js",
19
+ "exports": {
20
+ ".": {
21
+ "require": "./cjs/index.js",
22
+ "import": "./index.js"
23
+ },
24
+ "./ApiError": {
25
+ "require": "./cjs/ApiError.js",
26
+ "import": "./ApiError.js"
27
+ },
28
+ "./createApi": {
29
+ "require": "./cjs/createApi.js",
30
+ "import": "./createApi.js"
31
+ },
32
+ "./createApiResultFail": {
33
+ "require": "./cjs/createApiResultFail.js",
34
+ "import": "./createApiResultFail.js"
35
+ },
36
+ "./createApiResultOk": {
37
+ "require": "./cjs/createApiResultOk.js",
38
+ "import": "./createApiResultOk.js"
39
+ },
40
+ "./createSwrApi": {
41
+ "require": "./cjs/createSwrApi.js",
42
+ "import": "./createSwrApi.js"
43
+ },
44
+ "./nextApiResponse": {
45
+ "require": "./cjs/nextApiResponse.js",
46
+ "import": "./nextApiResponse.js"
47
+ },
48
+ "./nextApiResponse12": {
49
+ "require": "./cjs/nextApiResponse12.js",
50
+ "import": "./nextApiResponse12.js"
51
+ }
52
+ },
53
+ "peerDependencies": {},
54
+ "version": "2.0.0-beta.21"
24
55
  }
package/typings.d.ts CHANGED
@@ -15,7 +15,7 @@ type ExtractEndpointParams<T extends string> = string extends T
15
15
  ? { [k in Param]: string | number }
16
16
  : never;
17
17
 
18
- declare namespace Koine.Api {
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 { credentials: "include", referrerPolicy: "no-referrer" }
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
  //////////////////////////////////////////////////////////////////////////////
@@ -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.mjs DELETED
@@ -1,20 +0,0 @@
1
- import { __extends } from "tslib";
2
- /**
3
- * Custom `ApiError` class extending `Error` to throw in failed response.
4
- *
5
- * @see https://eslint.org/docs/rules/no-throw-literal
6
- * @see https://github.com/sindresorhus/ky/blob/main/source/errors/HTTPError.ts
7
- *
8
- */
9
- var ApiError = /** @class */ (function (_super) {
10
- __extends(ApiError, _super);
11
- function ApiError(result) {
12
- var _this = _super.call(this, "Request failed with ".concat(result.status, " ").concat(result.msg)) || this;
13
- _this.name = "ApiError";
14
- Object.assign(_this, result);
15
- return _this;
16
- }
17
- return ApiError;
18
- }(Error));
19
- export { ApiError };
20
- export default ApiError;
package/README.md DELETED
@@ -1 +0,0 @@
1
- # @koine/api
package/createSwrApi.mjs DELETED
@@ -1,87 +0,0 @@
1
- "use client";
2
- import { __assign, __awaiter, __generator } from "tslib";
3
- import isFunction from "@koine/utils/isFunction";
4
- import useSWR from "swr";
5
- import useSWRMutation from "swr/mutation";
6
- import createApi from "./createApi";
7
- function createUseApi(api, method) {
8
- return function useApi(endpoint, options, _config) {
9
- var _this = this;
10
- if (method === "get") {
11
- // const fetcher = async (_endpoint: TEndpoint) => {
12
- // try {
13
- // const { ok, data } = await api[method](_endpoint, {
14
- // ...(options || {}),
15
- // throwErr: true,
16
- // });
17
- // if (ok) {
18
- // return data;
19
- // }
20
- // throw new Error() as unknown as Koine.Api.EndpointResponseFail<TEndpoints, TEndpoint, TMethod>;
21
- // } catch(e) {
22
- // throw new Error() as unknown as Koine.Api.EndpointResponseFail<TEndpoints, TEndpoint, TMethod>;;
23
- // }
24
- // };
25
- // }
26
- var fetcher = function () { return __awaiter(_this, void 0, void 0, function () {
27
- var data;
28
- return __generator(this, function (_a) {
29
- switch (_a.label) {
30
- case 0: return [4 /*yield*/, api[method](endpoint, __assign(__assign({}, (options || {})), { throwErr: true }))];
31
- case 1:
32
- data = (_a.sent()).data;
33
- return [2 /*return*/, data];
34
- }
35
- });
36
- }); };
37
- var config_1 = _config;
38
- var shouldNotFetch = (config_1 === null || config_1 === void 0 ? void 0 : config_1.when) === false ||
39
- (isFunction(config_1 === null || config_1 === void 0 ? void 0 : config_1.when) && (config_1 === null || config_1 === void 0 ? void 0 : config_1.when()) === false);
40
- // <Data = any, Error = any>(key: Key, config: SWRConfigurationExtended<Data, Error, Fetcher<Data>> | undefined): SWRResponse<Data, Error>;
41
- // eslint-disable-next-line react-hooks/rules-of-hooks
42
- return useSWR(shouldNotFetch ? null : options ? [endpoint, options] : [endpoint], fetcher, config_1);
43
- }
44
- var config = _config;
45
- var sender = function (
46
- // if the first argument is an array the second tem are the base options
47
- // defined when calling the usePost/Put/etc. hook, these will be overriden
48
- // by the _options just here below
49
- _endpoint,
50
- // these are the options arriving when calling `trigger({ json, query, etc... })
51
- _options) { return __awaiter(_this, void 0, void 0, function () {
52
- var endpoint, options, _a, ok, data;
53
- return __generator(this, function (_b) {
54
- switch (_b.label) {
55
- case 0:
56
- endpoint = Array.isArray(_endpoint) ? _endpoint[0] : _endpoint;
57
- options = Array.isArray(_endpoint) ? _endpoint[1] : {};
58
- return [4 /*yield*/, api[method](endpoint, __assign(__assign(__assign({}, options), (_options.arg || {})), { throwErr: true }))];
59
- case 1:
60
- _a = _b.sent(), ok = _a.ok, data = _a.data;
61
- return [2 /*return*/, ok ? data : data];
62
- }
63
- });
64
- }); };
65
- // config.fetcher = sender;
66
- // eslint-disable-next-line react-hooks/rules-of-hooks
67
- return useSWRMutation(
68
- // @ts-expect-error FIXME: I can't get it...
69
- options ? [endpoint, options] : endpoint, sender, config);
70
- };
71
- }
72
- /**
73
- * It creates an api client extended with auto-generated SWR wrapper hooks
74
- */
75
- export var createSwrApi = function () {
76
- var args = [];
77
- for (var _i = 0; _i < arguments.length; _i++) {
78
- args[_i] = arguments[_i];
79
- }
80
- var api = createApi.apply(void 0, args);
81
- ["get", "post", "put", "patch", "delete"].forEach(function (method) {
82
- var hookName = "use".concat(method.charAt(0).toUpperCase() + method.slice(1));
83
- api[hookName] = createUseApi(api, method);
84
- });
85
- return api;
86
- };
87
- export default createSwrApi;
package/index.mjs DELETED
@@ -1,4 +0,0 @@
1
- export { ApiError } from "./ApiError";
2
- export { createApi } from "./createApi";
3
- export { createSwrApi } from "./createSwrApi";
4
- export { nextApiResponse } from "./nextApiResponse";
@@ -1,5 +0,0 @@
1
- export var nextApiResponse = function (nextRes, result) {
2
- // nextRes.status(result.status).json(result.data || result.msg);
3
- nextRes.status(result.status).json(result);
4
- };
5
- export default nextApiResponse;