70 lines
1.9 KiB
TypeScript
70 lines
1.9 KiB
TypeScript
import { drizzle } from "drizzle-orm/node-postgres";
|
|
import { iotData as iotDataSchema } from "./schema/iot-sensors-data.schema.ts";
|
|
import pg from "pg";
|
|
import * as pgCore from "drizzle-orm/pg-core";
|
|
import { eq } from "drizzle-orm/expressions";
|
|
|
|
// Use pg driver.
|
|
const { Pool } = pg;
|
|
|
|
function createConnectionString(
|
|
user: string,
|
|
password: string,
|
|
host: string,
|
|
port: string | number,
|
|
db: string
|
|
) {
|
|
return `postgresql://${user}:${password}@${host}:${port}/${db}`
|
|
}
|
|
|
|
// Instantiate Drizzle client with pg driver and schema.
|
|
export const db = drizzle({
|
|
client: new Pool({
|
|
connectionString: createConnectionString(
|
|
Deno.env.get("DB_USER")!,
|
|
Deno.env.get("DB_PASSWORD")!,
|
|
Deno.env.get("DB_HOST")!,
|
|
Deno.env.get("DB_PORT")!,
|
|
Deno.env.get("DB")!
|
|
),
|
|
}),
|
|
schema: { iotDataSchema },
|
|
});
|
|
|
|
export type IoTDatum = typeof iotDataSchema.$inferInsert
|
|
|
|
|
|
export async function insertIoTDatum(iotDatum: typeof iotDataSchema.$inferInsert) {
|
|
return await db.insert(iotDataSchema).values(iotDatum)
|
|
}
|
|
|
|
|
|
export async function findIoTDatumByID(datumID: number) {
|
|
return await db.select().from(iotDataSchema).where(
|
|
eq(iotDataSchema.id, datumID)
|
|
)
|
|
}
|
|
|
|
// UGLY: Downcasting from bigint to number
|
|
export async function findIoTDatumByDeviceID(deviceID: bigint) {
|
|
const _deviceID: number = Number(deviceID)
|
|
return await db.select().from(iotDataSchema).where(
|
|
eq(iotDataSchema.deviceID, _deviceID)
|
|
)
|
|
}
|
|
|
|
export async function getPage(offset: number = 0, numberOfResults: number = 100) {
|
|
return await db
|
|
.select()
|
|
.from(iotDataSchema)
|
|
.orderBy(iotDataSchema.id)
|
|
.limit(numberOfResults)
|
|
.offset(offset)
|
|
}
|
|
|
|
|
|
export async function deleteIoTDatumByID(datumID: number) {
|
|
return await db.delete(iotDataSchema).where(
|
|
eq(iotDataSchema.id, datumID)
|
|
)
|
|
} |