Skip to content

Instantly share code, notes, and snippets.

@sachitsac
Created December 22, 2022 05:10
Show Gist options
  • Save sachitsac/33caed8e063cfc7fe522c0b4ce9ad5e9 to your computer and use it in GitHub Desktop.
Save sachitsac/33caed8e063cfc7fe522c0b4ce9ad5e9 to your computer and use it in GitHub Desktop.
export const mockedCorrectUser = {
name: "abc",
uuid: "b3963682-08f1-4946-b832-3b7fe4d45f6c",
email: "me@awesome.com",
verified: true,
};
export const invalidUser = {
name: "abc",
uuid: "abc",
email: "me",
};
export const invalidUserUuid = {
name: "abc",
uuid: "abc",
email: "me@example.com",
verified: true,
};
export const logIsUser = (user: any, isUser: (user: any) => boolean) => {
console.log(`Assert Passed data object is a User ? ${isUser(user)}`);
};
import {
invalidUser,
invalidUserUuid,
logIsUser,
mockedCorrectUser,
} from "./test_data";
interface User {
name: string;
email: string;
uuid: string;
verified: boolean;
}
const isUuidV4 = (uuid: string) => {
return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(
uuid
);
};
const isUser = (obj: any): obj is User => {
if (!obj?.name || typeof obj.name !== "string") {
return false;
}
if (!obj?.email || typeof obj.email !== "string") {
return false;
}
if (!obj?.uuid || typeof obj.uuid !== "string" || !isUuidV4(obj.uuid)) {
return false;
}
if (!obj?.verified || typeof obj.verified !== "boolean") {
return false;
}
return true;
};
logIsUser(mockedCorrectUser, isUser);
logIsUser(invalidUser, isUser);
logIsUser(invalidUserUuid, isUser);
import z from "zod";
import {
invalidUser,
invalidUserUuid,
logIsUser,
mockedCorrectUser,
} from "./test_data";
const userSchema = z.object({
uuid: z.string().uuid(),
name: z.string().optional(),
email: z.string().email(),
verified: z.boolean().default(false),
});
type User = z.infer<typeof userSchema>;
const isUser = (obj: any): obj is User => {
if (!userSchema.safeParse(obj).success) {
return false;
}
return true;
};
logIsUser(mockedCorrectUser, isUser);
logIsUser(invalidUser, isUser);
logIsUser(invalidUserUuid, isUser);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment