aspi 2.8.0 → 2.9.1

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/README.md CHANGED
@@ -116,12 +116,12 @@ try {
116
116
 
117
117
  Every response mode surfaces the same tagged error variants:
118
118
 
119
- | Tag | When |
120
- | ------------------ | ------------------------------------------------------------------------------------------------- |
121
- | `aspiError` | Any non-2xx response with no matching custom handler |
122
- | `jsonParseError` | Response body could not be parsed as JSON |
123
- | `schemaParseError` | Response (or request body) failed schema validation (when `.schema()` or `.bodySchema()` is used) |
124
- | _custom_ | Any tag you define via `.error()` or a convenience shortcut |
119
+ | Tag | When |
120
+ | ------------------ | --------------------------------------------------------------------------------------------------------------------------------- |
121
+ | `aspiError` | Any non-2xx response with no matching custom handler |
122
+ | `jsonParseError` | Response body could not be parsed as JSON |
123
+ | `schemaParseError` | Response, request body, or query params failed schema validation (when `.schema()`, `.bodySchema()`, or `.querySchema()` is used) |
124
+ | _custom_ | Any tag you define via `.error()` or a convenience shortcut |
125
125
 
126
126
  ### Custom error mapping
127
127
 
@@ -250,6 +250,39 @@ console.log(api.get('/todos').setQueryParams({ page: '2' }).url());
250
250
  // → https://api.example.com/todos?page=2
251
251
  ```
252
252
 
253
+ #### Query schema validation
254
+
255
+ Just like request bodies, query parameters can be validated with `.querySchema()`. The schema transforms the input and `setQueryParams()` is typed to accept only the schema's input shape.
256
+
257
+ ```ts
258
+ import { z } from 'zod';
259
+
260
+ const ListTodosQuery = z.object({
261
+ page: z.number().default(1),
262
+ limit: z.number().default(10),
263
+ sort: z.enum(['asc', 'desc']).default('asc'),
264
+ });
265
+
266
+ const result = await api
267
+ .get('/todos')
268
+ .querySchema(ListTodosQuery)
269
+ .setQueryParams({ page: 1, limit: 20 })
270
+ .withResult()
271
+ .json();
272
+
273
+ // If validation fails, error.tag === 'schemaParseError' and no network call is made
274
+ Result.match(result, {
275
+ onOk: ({ data }) => console.log(data),
276
+ onErr: (err) => {
277
+ if (err.tag === 'schemaParseError') {
278
+ console.error('Invalid query params:', err.data);
279
+ }
280
+ },
281
+ });
282
+ ```
283
+
284
+ If the schema transforms values (e.g. applying defaults or coercion), the transformed output is what gets serialized into the URL. Async schema validators are also supported.
285
+
253
286
  ### Headers
254
287
 
255
288
  ```ts
@@ -332,6 +365,8 @@ Result.match(result, {
332
365
  });
333
366
  ```
334
367
 
368
+ > `.querySchema()` and `.bodySchema()` work the same way — they validate at the edge of the request builder and short-circuit the network call on failure, producing a `schemaParseError` in the error union.
369
+
335
370
  ---
336
371
 
337
372
  ## Middleware
@@ -535,7 +570,7 @@ These methods are available on the `Aspi` instance and affect all requests creat
535
570
  | `withTuple()` | Switch all requests back to tuple mode |
536
571
  | `.error(tag, status, cb)` | Map an HTTP status to a typed error |
537
572
 
538
- Per-request methods (`api.get('/…').setQueryParams(…)`, `.schema(…)`, `.bodyJson(…)`, etc.) override the global config for that call only.
573
+ Per-request methods (`api.get('/…').setQueryParams(…)`, `.schema(…)`, `.querySchema(…)`, `.bodyJson(…)`, etc.) override the global config for that call only.
539
574
 
540
575
  ---
541
576
 
package/dist/index.cjs CHANGED
@@ -327,6 +327,10 @@ var Request = class {
327
327
  #bodySchemaIssues = [];
328
328
  #bodySchemaAsyncResult = null;
329
329
  #bodySchemaAsyncBody = null;
330
+ #querySchema = null;
331
+ #querySchemaIssues = [];
332
+ #querySchemaAsyncResult = null;
333
+ #querySchemaAsyncParams = null;
330
334
  #throwOnError = false;
331
335
  #capabilities = [];
332
336
  constructor(method, path, requestOptions, capabilities = []) {
@@ -679,6 +683,26 @@ var Request = class {
679
683
  };
680
684
  return this;
681
685
  }
686
+ /**
687
+ * Sets a validation schema for the query parameters using a StandardSchemaV1 schema.
688
+ * @template TSchema Type parameter extending StandardSchemaV1
689
+ * @param schema The schema to validate query parameters against
690
+ * @returns The request instance for chaining with updated error type
691
+ * @example
692
+ * const querySchema = z.object({
693
+ * page: z.number(),
694
+ * limit: z.number()
695
+ * });
696
+ *
697
+ * const request = new Request('/users', config);
698
+ * request
699
+ * .querySchema(querySchema)
700
+ * .setQueryParams({ page: 1, limit: 10 });
701
+ */
702
+ querySchema(schema) {
703
+ this.#querySchema = schema;
704
+ return this;
705
+ }
682
706
  /**
683
707
  * Sets the query parameters for the request URL.
684
708
  *
@@ -713,29 +737,19 @@ var Request = class {
713
737
  * request.setQueryParams(qp);
714
738
  */
715
739
  setQueryParams(params) {
716
- let qp;
717
- if (params instanceof URLSearchParams) {
718
- qp = new URLSearchParams(params);
719
- } else if (typeof params === "string") {
720
- qp = new URLSearchParams(params);
721
- } else if (Array.isArray(params)) {
722
- qp = new URLSearchParams();
723
- for (const entry of params) {
724
- if (Array.isArray(entry) && entry.length === 2) {
725
- qp.append(String(entry[0]), String(entry[1]));
726
- }
727
- }
728
- } else if (typeof params === "object" && params !== null) {
729
- qp = new URLSearchParams();
730
- for (const [key, value] of Object.entries(
731
- params
732
- )) {
733
- qp.append(key, String(value));
740
+ if (this.#querySchema) {
741
+ const data = this.#querySchema["~standard"].validate(params);
742
+ if (data instanceof Promise) {
743
+ this.#querySchemaAsyncResult = data;
744
+ this.#querySchemaAsyncParams = params;
745
+ } else if (data.issues) {
746
+ this.#querySchemaIssues = data.issues;
747
+ } else {
748
+ this.#queryParams = this.#valueToQueryParams(data.value);
734
749
  }
735
750
  } else {
736
- qp = new URLSearchParams();
751
+ this.#queryParams = this.#valueToQueryParams(params);
737
752
  }
738
- this.#queryParams = qp;
739
753
  return this;
740
754
  }
741
755
  /**
@@ -1061,6 +1075,33 @@ var Request = class {
1061
1075
  );
1062
1076
  return this.#mapResponse(output);
1063
1077
  }
1078
+ #valueToQueryParams(value) {
1079
+ if (value instanceof URLSearchParams) {
1080
+ return new URLSearchParams(value);
1081
+ }
1082
+ if (typeof value === "string") {
1083
+ return new URLSearchParams(value);
1084
+ }
1085
+ if (Array.isArray(value)) {
1086
+ const qp = new URLSearchParams();
1087
+ for (const entry of value) {
1088
+ if (Array.isArray(entry) && entry.length === 2) {
1089
+ qp.append(String(entry[0]), String(entry[1]));
1090
+ }
1091
+ }
1092
+ return qp;
1093
+ }
1094
+ if (typeof value === "object" && value !== null) {
1095
+ const qp = new URLSearchParams();
1096
+ for (const [key, val] of Object.entries(
1097
+ value
1098
+ )) {
1099
+ qp.append(key, String(val));
1100
+ }
1101
+ return qp;
1102
+ }
1103
+ return new URLSearchParams();
1104
+ }
1064
1105
  #url() {
1065
1106
  if (this.#path.startsWith("http://") || this.#path.startsWith("https://")) {
1066
1107
  const absolute = new URL(this.#path);
@@ -1235,6 +1276,21 @@ var Request = class {
1235
1276
  new CustomError("schemaParseError", this.#bodySchemaIssues)
1236
1277
  );
1237
1278
  }
1279
+ if (this.#querySchemaAsyncResult) {
1280
+ const data = await this.#querySchemaAsyncResult;
1281
+ if (data.issues) {
1282
+ this.#querySchemaIssues = data.issues;
1283
+ } else {
1284
+ this.#queryParams = this.#valueToQueryParams(data.value);
1285
+ }
1286
+ this.#querySchemaAsyncResult = null;
1287
+ this.#querySchemaAsyncParams = null;
1288
+ }
1289
+ if (this.#querySchemaIssues.length) {
1290
+ return err(
1291
+ new CustomError("schemaParseError", this.#querySchemaIssues)
1292
+ );
1293
+ }
1238
1294
  const request = this.#request();
1239
1295
  const { retries, retryDelay, retryOn, retryWhile, onRetry } = this.#sanitisedRetryConfig();
1240
1296
  try {
package/dist/index.d.cts CHANGED
@@ -1139,6 +1139,28 @@ declare class Request<Method extends HttpMethods, TRequest extends AspiRequestIn
1139
1139
  error<Tag extends string, A extends {}>(tag: Tag, status: HttpErrorStatus, cb: CustomErrorCb<TRequest, A>): Request<Method, TRequest, Merge<Omit<Opts, "error">, {
1140
1140
  error: { [K in Tag | keyof Opts["error"]]: K extends Tag ? CustomError<Tag, A> : Opts["error"][K]; };
1141
1141
  }>>;
1142
+ /**
1143
+ * Sets a validation schema for the query parameters using a StandardSchemaV1 schema.
1144
+ * @template TSchema Type parameter extending StandardSchemaV1
1145
+ * @param schema The schema to validate query parameters against
1146
+ * @returns The request instance for chaining with updated error type
1147
+ * @example
1148
+ * const querySchema = z.object({
1149
+ * page: z.number(),
1150
+ * limit: z.number()
1151
+ * });
1152
+ *
1153
+ * const request = new Request('/users', config);
1154
+ * request
1155
+ * .querySchema(querySchema)
1156
+ * .setQueryParams({ page: 1, limit: 10 });
1157
+ */
1158
+ querySchema<TSchema extends StandardSchemaV1>(schema: TSchema): Request<Method, TRequest, Omit<Opts, "querySchema"> & {
1159
+ querySchema: TSchema;
1160
+ error: Opts["error"] & {
1161
+ schemaParseError: CustomError<"schemaParseError", StandardSchemaV1.FailureResult["issues"]>;
1162
+ };
1163
+ }>;
1142
1164
  /**
1143
1165
  * Sets the query parameters for the request URL.
1144
1166
  *
@@ -1172,7 +1194,9 @@ declare class Request<Method extends HttpMethods, TRequest extends AspiRequestIn
1172
1194
  * const qp = new URLSearchParams({ page: '1' });
1173
1195
  * request.setQueryParams(qp);
1174
1196
  */
1175
- setQueryParams<T = any>(params: T): Request<Method, TRequest, Merge<Omit<Opts, "queryParams">, {
1197
+ setQueryParams<T extends Opts extends {
1198
+ querySchema: infer S extends StandardSchemaV1;
1199
+ } ? StandardSchemaV1.InferInput<S> : any>(params: T): Request<Method, TRequest, Merge<Omit<Opts, "queryParams">, {
1176
1200
  queryParams: T;
1177
1201
  }>>;
1178
1202
  /**
package/dist/index.d.ts CHANGED
@@ -1139,6 +1139,28 @@ declare class Request<Method extends HttpMethods, TRequest extends AspiRequestIn
1139
1139
  error<Tag extends string, A extends {}>(tag: Tag, status: HttpErrorStatus, cb: CustomErrorCb<TRequest, A>): Request<Method, TRequest, Merge<Omit<Opts, "error">, {
1140
1140
  error: { [K in Tag | keyof Opts["error"]]: K extends Tag ? CustomError<Tag, A> : Opts["error"][K]; };
1141
1141
  }>>;
1142
+ /**
1143
+ * Sets a validation schema for the query parameters using a StandardSchemaV1 schema.
1144
+ * @template TSchema Type parameter extending StandardSchemaV1
1145
+ * @param schema The schema to validate query parameters against
1146
+ * @returns The request instance for chaining with updated error type
1147
+ * @example
1148
+ * const querySchema = z.object({
1149
+ * page: z.number(),
1150
+ * limit: z.number()
1151
+ * });
1152
+ *
1153
+ * const request = new Request('/users', config);
1154
+ * request
1155
+ * .querySchema(querySchema)
1156
+ * .setQueryParams({ page: 1, limit: 10 });
1157
+ */
1158
+ querySchema<TSchema extends StandardSchemaV1>(schema: TSchema): Request<Method, TRequest, Omit<Opts, "querySchema"> & {
1159
+ querySchema: TSchema;
1160
+ error: Opts["error"] & {
1161
+ schemaParseError: CustomError<"schemaParseError", StandardSchemaV1.FailureResult["issues"]>;
1162
+ };
1163
+ }>;
1142
1164
  /**
1143
1165
  * Sets the query parameters for the request URL.
1144
1166
  *
@@ -1172,7 +1194,9 @@ declare class Request<Method extends HttpMethods, TRequest extends AspiRequestIn
1172
1194
  * const qp = new URLSearchParams({ page: '1' });
1173
1195
  * request.setQueryParams(qp);
1174
1196
  */
1175
- setQueryParams<T = any>(params: T): Request<Method, TRequest, Merge<Omit<Opts, "queryParams">, {
1197
+ setQueryParams<T extends Opts extends {
1198
+ querySchema: infer S extends StandardSchemaV1;
1199
+ } ? StandardSchemaV1.InferInput<S> : any>(params: T): Request<Method, TRequest, Merge<Omit<Opts, "queryParams">, {
1176
1200
  queryParams: T;
1177
1201
  }>>;
1178
1202
  /**
package/dist/index.js CHANGED
@@ -297,6 +297,10 @@ var Request = class {
297
297
  #bodySchemaIssues = [];
298
298
  #bodySchemaAsyncResult = null;
299
299
  #bodySchemaAsyncBody = null;
300
+ #querySchema = null;
301
+ #querySchemaIssues = [];
302
+ #querySchemaAsyncResult = null;
303
+ #querySchemaAsyncParams = null;
300
304
  #throwOnError = false;
301
305
  #capabilities = [];
302
306
  constructor(method, path, requestOptions, capabilities = []) {
@@ -649,6 +653,26 @@ var Request = class {
649
653
  };
650
654
  return this;
651
655
  }
656
+ /**
657
+ * Sets a validation schema for the query parameters using a StandardSchemaV1 schema.
658
+ * @template TSchema Type parameter extending StandardSchemaV1
659
+ * @param schema The schema to validate query parameters against
660
+ * @returns The request instance for chaining with updated error type
661
+ * @example
662
+ * const querySchema = z.object({
663
+ * page: z.number(),
664
+ * limit: z.number()
665
+ * });
666
+ *
667
+ * const request = new Request('/users', config);
668
+ * request
669
+ * .querySchema(querySchema)
670
+ * .setQueryParams({ page: 1, limit: 10 });
671
+ */
672
+ querySchema(schema) {
673
+ this.#querySchema = schema;
674
+ return this;
675
+ }
652
676
  /**
653
677
  * Sets the query parameters for the request URL.
654
678
  *
@@ -683,29 +707,19 @@ var Request = class {
683
707
  * request.setQueryParams(qp);
684
708
  */
685
709
  setQueryParams(params) {
686
- let qp;
687
- if (params instanceof URLSearchParams) {
688
- qp = new URLSearchParams(params);
689
- } else if (typeof params === "string") {
690
- qp = new URLSearchParams(params);
691
- } else if (Array.isArray(params)) {
692
- qp = new URLSearchParams();
693
- for (const entry of params) {
694
- if (Array.isArray(entry) && entry.length === 2) {
695
- qp.append(String(entry[0]), String(entry[1]));
696
- }
697
- }
698
- } else if (typeof params === "object" && params !== null) {
699
- qp = new URLSearchParams();
700
- for (const [key, value] of Object.entries(
701
- params
702
- )) {
703
- qp.append(key, String(value));
710
+ if (this.#querySchema) {
711
+ const data = this.#querySchema["~standard"].validate(params);
712
+ if (data instanceof Promise) {
713
+ this.#querySchemaAsyncResult = data;
714
+ this.#querySchemaAsyncParams = params;
715
+ } else if (data.issues) {
716
+ this.#querySchemaIssues = data.issues;
717
+ } else {
718
+ this.#queryParams = this.#valueToQueryParams(data.value);
704
719
  }
705
720
  } else {
706
- qp = new URLSearchParams();
721
+ this.#queryParams = this.#valueToQueryParams(params);
707
722
  }
708
- this.#queryParams = qp;
709
723
  return this;
710
724
  }
711
725
  /**
@@ -1031,6 +1045,33 @@ var Request = class {
1031
1045
  );
1032
1046
  return this.#mapResponse(output);
1033
1047
  }
1048
+ #valueToQueryParams(value) {
1049
+ if (value instanceof URLSearchParams) {
1050
+ return new URLSearchParams(value);
1051
+ }
1052
+ if (typeof value === "string") {
1053
+ return new URLSearchParams(value);
1054
+ }
1055
+ if (Array.isArray(value)) {
1056
+ const qp = new URLSearchParams();
1057
+ for (const entry of value) {
1058
+ if (Array.isArray(entry) && entry.length === 2) {
1059
+ qp.append(String(entry[0]), String(entry[1]));
1060
+ }
1061
+ }
1062
+ return qp;
1063
+ }
1064
+ if (typeof value === "object" && value !== null) {
1065
+ const qp = new URLSearchParams();
1066
+ for (const [key, val] of Object.entries(
1067
+ value
1068
+ )) {
1069
+ qp.append(key, String(val));
1070
+ }
1071
+ return qp;
1072
+ }
1073
+ return new URLSearchParams();
1074
+ }
1034
1075
  #url() {
1035
1076
  if (this.#path.startsWith("http://") || this.#path.startsWith("https://")) {
1036
1077
  const absolute = new URL(this.#path);
@@ -1205,6 +1246,21 @@ var Request = class {
1205
1246
  new CustomError("schemaParseError", this.#bodySchemaIssues)
1206
1247
  );
1207
1248
  }
1249
+ if (this.#querySchemaAsyncResult) {
1250
+ const data = await this.#querySchemaAsyncResult;
1251
+ if (data.issues) {
1252
+ this.#querySchemaIssues = data.issues;
1253
+ } else {
1254
+ this.#queryParams = this.#valueToQueryParams(data.value);
1255
+ }
1256
+ this.#querySchemaAsyncResult = null;
1257
+ this.#querySchemaAsyncParams = null;
1258
+ }
1259
+ if (this.#querySchemaIssues.length) {
1260
+ return err(
1261
+ new CustomError("schemaParseError", this.#querySchemaIssues)
1262
+ );
1263
+ }
1208
1264
  const request = this.#request();
1209
1265
  const { retries, retryDelay, retryOn, retryWhile, onRetry } = this.#sanitisedRetryConfig();
1210
1266
  try {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "aspi",
3
3
  "description": "Rest API client for typescript projects with chain of responsibility design pattern.",
4
- "version": "2.8.0",
4
+ "version": "2.9.1",
5
5
  "module": "src/index.ts",
6
6
  "type": "module",
7
7
  "devDependencies": {
@@ -13,7 +13,7 @@
13
13
  "zod": "^3.24.1"
14
14
  },
15
15
  "peerDependencies": {
16
- "typescript": "^5.0.0"
16
+ "typescript": ">=5"
17
17
  },
18
18
  "author": {
19
19
  "email": "harshpareek91@gmai.com",