1+ import {
2+ APIObjectAssertionProps ,
3+ LiteralAssertionProps ,
4+ } from "@/types/assertions" ;
15import * as z from "zod" ;
26import { SquareCloudAPIError } from "../structures" ;
37
4- const stringSchema = z . coerce . string ( ) ;
5- const booleanSchema = z . coerce . boolean ( ) ;
6- const pathLikeSchema = z . string ( ) . or ( z . instanceof ( Buffer ) ) ;
7-
8- export function assertString (
9- value : unknown ,
10- code ?: string ,
11- ) : asserts value is string {
12- handleAssertion ( { schema : stringSchema , expect : "string" , value, code } ) ;
13- }
14-
15- export function assertBoolean (
16- value : unknown ,
17- code ?: string ,
18- ) : asserts value is boolean {
19- handleAssertion ( { schema : booleanSchema , expect : "boolean" , value, code } ) ;
20- }
21-
22- export function assertPathLike (
23- value : unknown ,
24- code ?: string ,
25- ) : asserts value is string | Buffer {
26- handleAssertion ( {
27- schema : pathLikeSchema ,
28- expect : "string or Buffer" ,
29- value,
30- code,
31- } ) ;
32- }
33-
34- export function handleAssertion ( {
8+ export function handleLiteralAssertion ( {
359 schema,
3610 value,
3711 expect,
3812 code,
39- } : {
40- schema : z . Schema ;
41- value : unknown ;
42- expect : string ;
43- code ?: string ;
44- } ) {
13+ } : LiteralAssertionProps ) {
4514 try {
4615 schema . parse ( value ) ;
4716 } catch {
@@ -51,3 +20,27 @@ export function handleAssertion({
5120 ) ;
5221 }
5322}
23+
24+ export function handleAPIObjectAssertion ( {
25+ schema,
26+ value,
27+ code,
28+ route,
29+ } : APIObjectAssertionProps ) {
30+ const name = code . toLowerCase ( ) . replaceAll ( "_" , " " ) ;
31+
32+ try {
33+ schema . parse ( value ) ;
34+ } catch ( err ) {
35+ const cause = err . errors ?. map ( ( err : z . ZodIssue ) => ( {
36+ ...err ,
37+ path : err . path . join ( " > " ) ,
38+ } ) ) ;
39+
40+ throw new SquareCloudAPIError (
41+ `INVALID_API_${ code } ` ,
42+ `Invalid ${ name } object received from API ${ route } ` ,
43+ { cause } ,
44+ ) ;
45+ }
46+ }
0 commit comments