feat(jslib): add `getAs` convenience function to UpObject
ci/woodpecker/push/woodpecker Pipeline was successful Details

main
Tomáš Mládek 2024-06-24 17:45:45 +02:00
parent e478305d9b
commit 0eba0f9968
3 changed files with 94 additions and 1 deletions

View File

@ -1,6 +1,6 @@
{
"name": "@upnd/upend",
"version": "0.5.5",
"version": "0.6.0",
"description": "Client library to interact with the UpEnd system.",
"main": "dist/index.js",
"types": "dist/index.d.ts",

View File

@ -98,6 +98,34 @@ export class UpObject {
return this.attr[attr]?.[0].value.c;
}
public getAs(attribute: string, as: "string"): string | undefined;
public getAs(attribute: string, as: "number"): number | undefined;
public getAs(attribute: string, as: "null"): null | undefined;
public getAs(
attribute: string,
as: "string" | "number" | "null",
): string | number | null | undefined {
const value = this.attr[attribute]?.[0].value;
if (as === undefined) {
return this.attr[attribute]?.[0].value.c;
} else if (as === "string") {
return value?.c?.toString();
} else if (as === "number") {
switch (value?.t) {
case "Number":
return value.c;
case "String": {
const converted = parseFloat(value.c);
return isNaN(converted) ? undefined : converted;
}
default:
return undefined;
}
} else if (as === "null") {
return value?.t === "Null" ? null : undefined;
}
}
public identify(): string[] {
return (this.attr["LBL"] || []).map((e) => String(e.value.c));
}

View File

@ -0,0 +1,65 @@
import { UpListing, UpObject } from "../";
function testObj() {
const listing = new UpListing({
a: {
entity: "test",
attribute: "string",
value: { t: "String", c: "hello" },
provenance: "test",
timestamp: "0",
user: "test",
},
b: {
entity: "test",
attribute: "number",
value: { t: "Number", c: 1 },
provenance: "test",
timestamp: "0",
user: "test",
},
c: {
entity: "test",
attribute: "null",
value: { t: "Null", c: null },
provenance: "test",
timestamp: "0",
user: "test",
},
d: {
entity: "test",
attribute: "stringy_number",
value: { t: "String", c: "3" },
provenance: "test",
timestamp: "0",
user: "test",
},
});
return new UpObject("test", listing);
}
describe("UpObject get function", () => {
test("getting as string works", () => {
const obj = testObj();
expect(obj.getAs("string", "string")).toBe("hello");
expect(obj.getAs("number", "string")).toBe("1");
expect(obj.getAs("null", "string")).toBe(undefined);
expect(obj.getAs("stringy_number", "string")).toBe("3");
});
test("getting as number works", () => {
const obj = testObj();
expect(obj.getAs("string", "number")).toBe(undefined);
expect(obj.getAs("number", "number")).toBe(1);
expect(obj.getAs("null", "number")).toBe(undefined);
expect(obj.getAs("stringy_number", "number")).toBe(3);
});
test("getting as null works", () => {
const obj = testObj();
expect(obj.getAs("string", "null")).toBe(undefined);
expect(obj.getAs("number", "null")).toBe(undefined);
expect(obj.getAs("null", "null")).toBe(null);
expect(obj.getAs("stringy_number", "null")).toBe(undefined);
});
});