File tree Expand file tree Collapse file tree 3 files changed +79
-0
lines changed Expand file tree Collapse file tree 3 files changed +79
-0
lines changed Original file line number Diff line number Diff line change 1+ import type { ZodIssue } from "zod" ;
2+ import {
3+ SquareCloudBlobError ,
4+ SquareCloudValidationError ,
5+ } from "../structures/error" ;
6+ import type {
7+ APIObjectAssertionProps ,
8+ LiteralAssertionProps ,
9+ } from "../types/assertions" ;
10+
11+ export function handleLiteralAssertion ( {
12+ schema,
13+ value,
14+ expect,
15+ code,
16+ } : LiteralAssertionProps ) {
17+ try {
18+ schema . parse ( value ) ;
19+ } catch {
20+ throw new SquareCloudValidationError (
21+ code ? `INVALID_${ code } ` : "VALIDATION_ERROR" ,
22+ `Expect ${ expect } , got ${ typeof value } ` ,
23+ ) ;
24+ }
25+ }
26+
27+ export function handleAPIObjectAssertion ( {
28+ schema,
29+ value,
30+ code,
31+ route,
32+ } : APIObjectAssertionProps ) {
33+ const name = code . toLowerCase ( ) . replaceAll ( "_" , " " ) ;
34+
35+ try {
36+ return schema . parse ( value ) ;
37+ } catch ( err ) {
38+ const cause = err . errors ?. map ( ( err : ZodIssue ) => ( {
39+ ...err ,
40+ path : err . path . join ( " > " ) ,
41+ } ) ) ;
42+
43+ throw new SquareCloudBlobError (
44+ `INVALID_API_${ code } ` ,
45+ `Invalid ${ name } object received from API ${ route } ` ,
46+ { cause } ,
47+ ) ;
48+ }
49+ }
Original file line number Diff line number Diff line change 1+ import { stringSchema } from "../schemas/common" ;
2+ import { handleLiteralAssertion } from "./handlers" ;
3+
4+ export function assertString (
5+ value : unknown ,
6+ code ?: string ,
7+ ) : asserts value is string {
8+ handleLiteralAssertion ( {
9+ schema : stringSchema ,
10+ expect : "string" ,
11+ value,
12+ code,
13+ } ) ;
14+ }
Original file line number Diff line number Diff line change 1+ import type { ZodSchema } from "zod" ;
2+
3+ export type BaseAssertionProps = {
4+ schema : ZodSchema ;
5+ value : unknown ;
6+ code ?: string ;
7+ } ;
8+
9+ export type LiteralAssertionProps = BaseAssertionProps & {
10+ expect : string ;
11+ } ;
12+
13+ export type APIObjectAssertionProps = BaseAssertionProps & {
14+ code : string ;
15+ route : string ;
16+ } ;
You can’t perform that action at this time.
0 commit comments