Hook up syncing with postgres
This commit is contained in:
@@ -0,0 +1,58 @@
|
||||
import { PrintfulClient, ProductSyncer, WebflowClient, type SyncOptions } from "@blade-and-brawn/commerce";
|
||||
import { log } from "../util";
|
||||
import { db } from "../database/db";
|
||||
|
||||
export class SyncService {
|
||||
readonly productSyncer: ProductSyncer
|
||||
|
||||
constructor(printful: PrintfulClient, webflow: WebflowClient) {
|
||||
this.productSyncer = new ProductSyncer(printful, webflow, log);
|
||||
}
|
||||
|
||||
async start(filter: SyncOptions["filter"]) {
|
||||
let id: string | null = null;
|
||||
try {
|
||||
await this.productSyncer.sync({
|
||||
filter,
|
||||
onStart: async (startDate) => {
|
||||
const result = await db.insertInto("product_syncs")
|
||||
.values({
|
||||
started_at: startDate,
|
||||
printful_product_id_filter: filter?.printfulProductIds,
|
||||
syncing_printful_product_ids: []
|
||||
})
|
||||
.returning("id")
|
||||
.executeTakeFirstOrThrow();
|
||||
id = result.id;
|
||||
},
|
||||
onStep: async (printfulProductIds: number[]) => {
|
||||
if (!id) throw new Error("Expected sync run ID");
|
||||
await db.updateTable("product_syncs")
|
||||
.set({ syncing_printful_product_ids: printfulProductIds })
|
||||
.where("id", "=", id)
|
||||
.execute();
|
||||
},
|
||||
onCompletion: async (completionDate, duration) => {
|
||||
if (!id) throw new Error("Expected sync run ID");
|
||||
await db.updateTable("product_syncs")
|
||||
.set({ syncing_printful_product_ids: [], ended_at: completionDate, })
|
||||
.where("id", "=", id)
|
||||
.execute();
|
||||
}
|
||||
});
|
||||
}
|
||||
catch (err) {
|
||||
if (id) {
|
||||
await db.updateTable("product_syncs")
|
||||
.set({ syncing_printful_product_ids: [], ended_at: new Date(), has_failed: true })
|
||||
.where("id", "=", id)
|
||||
.execute();
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
async getActiveRun() {
|
||||
return await db.selectFrom("product_syncs").selectAll().where("ended_at", "is", null).executeTakeFirst();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user