-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathtinybird.ts
More file actions
59 lines (52 loc) · 1.72 KB
/
tinybird.ts
File metadata and controls
59 lines (52 loc) · 1.72 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
import {DateTime} from "luxon";
import {useRuntimeConfig} from "#imports";
export interface TinybirdResponse<T> {
data: T;
meta: {
name: string;
type: string;
}[],
rows: number;
'rows_before_limit_at_least': number;
statistics: {
elapsed: number;
rows_read: number;
bytes_read: number;
}
}
// TinyBird requires dates to be in a specific format, otherwise it returns an error.
function formatDateForTinyBird(date: DateTime): string {
return date.toFormat('yyyy-MM-dd 00:00:00') ?? '';
}
export async function fetchFromTinybird<T>(
path: string,
query: Record<string, string | number | boolean | string[] | DateTime | undefined | null>
): Promise<TinybirdResponse<T>> {
const config = useRuntimeConfig();
const {tinybirdBaseUrl, tinybirdToken} = config;
if (!tinybirdBaseUrl) {
throw new Error('Tinybird base URL is not defined');
}
if (!tinybirdToken) {
throw new Error('Tinybird token is not defined');
}
const url = `${tinybirdBaseUrl}${path}`;
// We don't want to send undefined, null, or empty values to TinyBird, so we remove those from the query.
// We also format DateTime objects so that TinyBird understands them.
const processedQuery = Object.fromEntries(
Object.entries(query)
.filter(([_, value]) => (value !== undefined) && (value !== '') && (value !== null))
.map(([key, value]) => [
key,
value instanceof DateTime
? formatDateForTinyBird(value)
: value
])
);
return await $fetch(url, {
query: processedQuery,
headers: {
Authorization: `Bearer ${tinybirdToken}`,
}
});
}