UNPKG

@tinybirdco/mockingbird

Version:
50 lines (49 loc) 1.91 kB
import fetch from "cross-fetch"; import { z } from "zod"; import { BaseGenerator, baseConfigSchema } from "./BaseGenerator"; const tinybirdConfigSchema = baseConfigSchema.merge(z.object({ endpoint: z.string(), datasource: z.string(), token: z.string(), })); export class TinybirdGenerator extends BaseGenerator { endpoints = { gcp_europe_west3: "https://api.tinybird.co", gcp_us_east4: "https://api.us-east.tinybird.co", aws_us_east_1: "https://api.us-east.aws.tinybird.co", aws_eu_central_1: "https://api.eu-central-1.aws.tinybird.co", aws_us_west_2: "https://api.us-west-2.aws.tinybird.co" }; events_path = "/v0/events"; constructor(config) { super(tinybirdConfigSchema.parse(config)); } async sendData(rows) { const params = { name: this.config.datasource, from: "mockingbird" }; const endpointURL = this.config.endpoint in this.endpoints ? this.endpoints[this.config.endpoint] : this.config.endpoint; const url = new URL(`${endpointURL}${this.events_path}`); Object.entries(params).forEach(([k, v]) => url.searchParams.set(k, v)); await fetch(url, { headers: { Authorization: `Bearer ${this.config.token}`, }, method: "POST", body: rows.map((d) => JSON.stringify(d)).join("\n"), }) .then((res) => { const contentType = res.headers.get("Content-Type"); if (contentType && contentType.toLowerCase().indexOf("text") > -1) { return res.text(); } return res.json(); }) .then((res) => { this.log("info", `Tinybird Response: ${JSON.stringify(res)}`); }) .catch((err) => { this.log("error", `Tinybird Error: ${JSON.stringify(err)}`); }); } }