1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import { APIField, APINode, APIPlainNode, TanaNode } from "https://esm.town/v/nbbaier/tanaTypes";
import { fetch } from "https://esm.town/v/std/fetch";
export class TanaAPIHelper {
private endpoint = "https://europe-west1-tagr-prod.cloudfunctions.net/addToNodeV2";
private get schemaNodeId() {
return `SCHEMA`;
}
private get inboxNodeID() {
return `INBOX`;
}
private get coreTemplateId() {
return "SYS_T01";
}
private get attrDefTemplateId() {
return "SYS_T02";
}
constructor(public token: string, public endpointUrl?: string) {
this.token = token;
if (endpointUrl) {
this.endpoint = endpointUrl;
}
}
async createFieldDefinitions(fields: APIPlainNode[]) {
const payload = {
targetNodeId: this.schemaNodeId,
nodes: fields.map((field) => ({
name: field.name,
description: field.description,
supertags: [{ id: this.attrDefTemplateId }],
})),
};
const createdFields = await this.makeRequest(payload);
return createdFields.map((field: any) => ({
name: field.name as string,
description: field.description as string,
id: field.nodeId as string,
}));
}
async createTagDefinition(node: APIPlainNode) {
if (!node.supertags) {
node.supertags = [];
}
node.supertags.push({ id: this.coreTemplateId });
const payload = {
targetNodeId: this.schemaNodeId,
nodes: [node],
};
const createdTag = await this.makeRequest(payload);
return createdTag[0].nodeId;
}
async createNode(node: APIPlainNode, targetNodeId?: string): Promise<TanaNode[]> {
const payload = {
targetNodeId: targetNodeId,
nodes: [node],
};
const createdNode = await this.makeRequest(payload);
return createdNode;
}
private async makeRequest(
payload: { targetNodeId?: string } & ({ nodes: (APINode | APIField)[] } | { setName: string }),
): Promise<TanaNode[]> {
const response = await fetch(this.endpoint, {
method: "POST",
headers: {
Authorization: "Bearer " + this.token,
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
});
if (response.status === 200 || response.status === 201) {
const json = await response.json();
if ("setName" in payload) {
return [json] as any as TanaNode[];
} else {
return (json as any).children as TanaNode[];
}
}
console.log(await response.text());
throw new Error(`${response.status} ${response.statusText}`);
}
}
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
October 27, 2023