Skip to content

Commit fc10ac4

Browse files
committed
create assertions
1 parent ba2eb09 commit fc10ac4

File tree

3 files changed

+79
-0
lines changed

3 files changed

+79
-0
lines changed

src/assertions/handlers.ts

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
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+
}

src/assertions/literal.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
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+
}

src/types/assertions.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
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+
};

0 commit comments

Comments
 (0)