@yopem/object-parser
Version:
117 lines (116 loc) • 3 kB
JavaScript
// src/index.ts
var ObjectParser = class _ObjectParser {
value;
constructor(value) {
this.value = value;
}
has(...path) {
if (path.length < 1) {
throw new TypeError("Invalid path");
}
let value = this.value;
for (const key of path) {
if (typeof value !== "object" || value === null) {
return false;
}
if (!(key in value)) {
return false;
}
value = value[key];
}
return true;
}
get(...path) {
if (path.length < 1) {
throw new TypeError("Invalid path");
}
let value = this.value;
for (let i = 0; i < path.length; i++) {
if (typeof value !== "object" || value === null) {
throw new Error(
`Value in path ${path.slice(0, i + 1).join(".")} is not an object`
);
}
if (!(path[i] in value)) {
throw new Error(`Path ${path.slice(0, i + 1).join(".")} does not exist`);
}
value = value[path[i]];
}
return value;
}
isString(...path) {
return typeof this.get(...path) === "string";
}
getString(...path) {
const value = this.get(...path);
if (typeof value !== "string") {
throw new Error(`Value in path ${path.join(".")} is not a string`);
}
return value;
}
isNumber(...path) {
return typeof this.get(...path) === "number";
}
getNumber(...path) {
const value = this.get(...path);
if (typeof value !== "number") {
throw new Error(`Value in path ${path.join(".")} is not a number`);
}
return value;
}
isBoolean(...path) {
return typeof this.get(...path) === "boolean";
}
getBoolean(...path) {
const value = this.get(...path);
if (typeof value !== "boolean") {
throw new Error(`Value in path ${path.join(".")} is not a boolean`);
}
return value;
}
isBigInt(...path) {
return typeof this.get(...path) === "bigint";
}
getBigInt(...path) {
const value = this.get(...path);
if (typeof value !== "bigint") {
throw new Error(`Value in path ${path.join(".")} is not a bigint`);
}
return value;
}
isObject(...path) {
const value = this.get(...path);
return typeof value === "object" && value !== null;
}
getObject(...path) {
const value = this.get(...path);
if (typeof value !== "object" || value === null) {
throw new Error(`Value in path ${path.join(".")} is not an object`);
}
return value;
}
isArray(...path) {
return Array.isArray(this.get(...path));
}
getArray(...path) {
const value = this.get(...path);
if (!Array.isArray(value)) {
throw new Error(`Value in path ${path.join(".")} is not an array`);
}
return value;
}
isNull(...path) {
const value = this.get(...path);
return value === null;
}
isUndefined(...path) {
const value = this.get(...path);
return value === void 0;
}
createParser(...path) {
return new _ObjectParser(this.getObject(...path));
}
};
export {
ObjectParser
};