-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnovaDb.ts
More file actions
166 lines (151 loc) · 6.21 KB
/
novaDb.ts
File metadata and controls
166 lines (151 loc) · 6.21 KB
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
import type {
INovaDbObjectType,
INovaDbRange,
INovaDbResult,
IObjectCountResult,
NovaDbObject,
ObjectType,
} from "./api.types";
import { Transform } from "stream";
import http from "http";
import https from "https";
import { expandQueryParams } from "~/utils";
const TOKEN = process.env.BASIC_AUTH_TOKEN;
const NOVADB_ENDPOINT = process.env.DELIVERY_API;
const NOVADB_BRANCH = process.env.BRANCH;
const BASIC = `Basic ${TOKEN}`;
/** Creates an Delivery API Request object including auth and content type headers */
const deliveryApiRequest = (url: string) => {
const headers = new Headers();
headers.set("Authorization", BASIC);
headers.set("Content-Type", "application/json; charset=utf-8");
return new Request(url, {
method: "GET",
headers,
});
};
/**
* Get a single scoped object
* @param id The object's id
* @param resolve A comma separated list of ApiIdentifiers attributes to be resolved and returned in a "refs" list. Wrong ApiIdentifiers are ignored
* @param filter A list of filter conditions joined with the AND operator '&&'. A condition is build from an ApiIdentifier, a compare operator (=, !=, <, >, <=, >=, :) and a value. Prefix with 'meta.' to access meta data.
*/
async function getObject<T extends NovaDbObject>(id: number | string, resolve?: string, filter?: string) {
const searchParams: string[] = [];
if (resolve) searchParams.push(`resolve=${resolve}`);
if (filter) searchParams.push(`filter=${filter}`);
var expandedUrl = expandQueryParams(`${NOVADB_ENDPOINT}branches/${NOVADB_BRANCH}/objects/${id}`, ...searchParams);
const request = deliveryApiRequest(expandedUrl);
const response = await fetch(request);
return response.json() as Promise<INovaDbResult<T>>;
}
/**
* Get a single typed and scoped object
* @param id The object's id
* @param type The object type as an ID or ApiIdentifier
* @param resolve A comma separated list of ApiIdentifiers attributes to be resolved and returned in a "refs" list. Wrong ApiIdentifiers are ignored
* @param filter A list of filter conditions joined with the AND operator '&&'. A condition is build from an ApiIdentifier, a compare operator (=, !=, <, >, <=, >=, :) and a value. Prefix with 'meta.' to access meta data.
*/
async function getObjectByType<T extends NovaDbObject>(
id: number | string,
type: ObjectType,
resolve?: string,
filter?: string
) {
const searchParams: string[] = [];
if (resolve) searchParams.push(`resolve=${resolve}`);
if (filter) searchParams.push(`filter=${filter}`);
searchParams.push("deleted=false");
const expandedUrl = expandQueryParams(
`${NOVADB_ENDPOINT}branches/${NOVADB_BRANCH}/types/${type}/objects/${id}`,
...searchParams
);
const request = deliveryApiRequest(expandedUrl);
const response = await fetch(request);
return response.json() as Promise<INovaDbResult<T>>;
}
/**
* Get a list of typed and scoped objects
* @param type The object type as an ID or ApiIdentifier
* @param resolve A comma separated list of ApiIdentifiers attributes to be resolved and returned in a "refs" list. Wrong ApiIdentifiers are ignored
* @param filter A list of filter conditions joined with the AND operator '&&'. A condition is build from an ApiIdentifier, a compare operator (=, !=, <, >, <=, >=, :) and a value. Prefix with 'meta.' to access meta data.
* @param sort A comma separated list of attribute IDs or ApiIdentifiers used as sort criteria. 'asc' or 'desc' can be used as an additional keyword to set the sort order. The default sort order is by object ID
* @param skip Skip a number of items. Must not be negative.
* @param take Take this number of items. Must be in the range 1..1000
*/
async function listObjects<T extends INovaDbObjectType>(
type: ObjectType,
resolve?: string,
filter?: string,
sort?: string,
skip: number = 0,
take: number = 100
) {
const searchParams: string[] = [];
if (resolve) searchParams.push(`resolve=${resolve}`);
if (filter) searchParams.push(`filter=${filter}`);
if (sort) searchParams.push(`sort=${sort}`);
searchParams.push(`skip=${skip}`);
searchParams.push(`take=${take}`);
searchParams.push("deleted=false");
const expandedUrl = expandQueryParams(
`${NOVADB_ENDPOINT}branches/${NOVADB_BRANCH}/types/${type}/objects`,
...searchParams
);
const request = deliveryApiRequest(expandedUrl);
const response = await fetch(request);
return response.json() as Promise<INovaDbRange<T>>;
}
async function getBinaryAsStream(src: string) {
try {
let srcUrl;
if (src.indexOf(".") === -1) srcUrl = new URL(`${NOVADB_ENDPOINT}branches/${NOVADB_BRANCH}/files/${src}`);
else srcUrl = new URL(`${NOVADB_ENDPOINT}files/${src}`);
const transformStream = new Transform();
let returnContentType = "";
transformStream._transform = function(chunk, _encoding, done) {
this.push(chunk);
done();
};
const options = {
hostname: srcUrl.hostname,
path: srcUrl.pathname,
headers: {
Authorization: BASIC,
},
};
if (process.env.NODE_ENV === "development") {
https.get(options, (res) => {
returnContentType = res.headers["content-type"] ?? "";
res.pipe(transformStream);
});
} else {
http.get(options, (res) => {
returnContentType = res.headers["content-type"] ?? "";
res.pipe(transformStream);
});
}
return { stream: transformStream, contentType: returnContentType };
} catch (error: unknown) {
console.error(`Error while getting binary from delivery api : ${src}`, error);
return { stream: new Transform(), contentType: "" };
}
}
/**
* Count typed objects
* @param type The ObjectType
* @param filter A list of filter conditions joined with the AND operator '&&'. A condition is build from an ApiIdentifier, a compare operator (=, !=, <, >, <=, >=, :) and a value. Prefix with 'meta.' to access meta data.
*/
async function getObjectCount(type: ObjectType, filter?: string) {
const searchParams: string[] = [];
if (filter) searchParams.push(`filter=${filter}`);
searchParams.push("deleted=false");
const expandedUrl = expandQueryParams(
`${NOVADB_ENDPOINT}branches/${NOVADB_BRANCH}/types/${type}/count`,
...searchParams
);
const request = deliveryApiRequest(expandedUrl);
const response = await fetch(request);
return response.json() as Promise<IObjectCountResult>;
}
export { getObject, getObjectCount, getObjectByType, listObjects, getBinaryAsStream };