guardz
Version:
A simple and lightweight TypeScript type guard library for runtime type validation.
77 lines (76 loc) • 2.22 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.invalidApiResponse = exports.validApiResponse = void 0;
exports.createApiResponseGuard = createApiResponseGuard;
exports.parseJsonPayload = parseJsonPayload;
const isArrayWithEachItem_1 = require("../../../typeguards/isArrayWithEachItem");
const isNumber_1 = require("../../../typeguards/isNumber");
const isOneOf_1 = require("../../../typeguards/isOneOf");
const isString_1 = require("../../../typeguards/isString");
const isType_1 = require("../../../typeguards/isType");
const isUndefinedOr_1 = require("../../../typeguards/isUndefinedOr");
exports.validApiResponse = {
data: {
users: [
{
id: 1,
name: 'Ada',
role: 'admin',
profile: { bio: 'Engineer' },
},
{
id: 2,
name: 'Grace',
role: 'user',
},
],
meta: {
total: 2,
page: 1,
},
},
};
exports.invalidApiResponse = {
data: {
users: [
{
id: 1,
name: 'Ada',
role: 'admin',
profile: { bio: 'Engineer' },
},
{
id: '2',
name: 'Grace',
role: 'superadmin',
},
],
meta: {
total: 2,
page: '1',
},
},
};
function createApiResponseGuard() {
const isUserProfile = (0, isType_1.isType)({
bio: isString_1.isString,
});
const isUser = (0, isType_1.isType)({
id: isNumber_1.isNumber,
name: isString_1.isString,
role: (0, isOneOf_1.isOneOf)('admin', 'user'),
profile: (0, isUndefinedOr_1.isUndefinedOr)(isUserProfile),
});
return (0, isType_1.isType)({
data: (0, isType_1.isType)({
users: (0, isArrayWithEachItem_1.isArrayWithEachItem)(isUser),
meta: (0, isType_1.isType)({
total: isNumber_1.isNumber,
page: isNumber_1.isNumber,
}),
}),
});
}
function parseJsonPayload(raw) {
return JSON.parse(raw);
}