98 lines
2.5 KiB
TypeScript
98 lines
2.5 KiB
TypeScript
/**
|
|
* This will monitor alpla purchase
|
|
*/
|
|
|
|
import { eq } from "drizzle-orm";
|
|
import { db } from "../db/db.controller.js";
|
|
import {
|
|
alplaPurchaseHistory,
|
|
type NewAlplaPurchaseHistory,
|
|
} from "../db/schema/alplapurchase.schema.js";
|
|
import { settings } from "../db/schema/settings.schema.js";
|
|
import { createLogger } from "../logger/logger.controller.js";
|
|
import { prodQuery } from "../prodSql/prodSqlQuery.controller.js";
|
|
import {
|
|
type SqlQuery,
|
|
sqlQuerySelector,
|
|
} from "../prodSql/prodSqlQuerySelector.utils.js";
|
|
import { createCronJob } from "../utils/croner.utils.js";
|
|
import { delay } from "../utils/delay.utils.js";
|
|
import { returnFunc } from "../utils/returnHelper.utils.js";
|
|
import { tryCatch } from "../utils/trycatch.utils.js";
|
|
|
|
const log = createLogger({ module: "purchase", subModule: "purchaseMonitor" });
|
|
|
|
export const monitorAlplaPurchase = async () => {
|
|
const purchaseMonitor = await db
|
|
.select()
|
|
.from(settings)
|
|
.where(eq(settings.name, "purchaseMonitor"));
|
|
|
|
const sqlQuery = sqlQuerySelector(`alplapurchase`) as SqlQuery;
|
|
|
|
if (!sqlQuery.success) {
|
|
return returnFunc({
|
|
success: false,
|
|
level: "error",
|
|
module: "purchase",
|
|
subModule: "query",
|
|
message: `Error getting alpla purchase info`,
|
|
data: [sqlQuery.message],
|
|
notify: false,
|
|
});
|
|
}
|
|
|
|
if (purchaseMonitor[0]?.active) {
|
|
createCronJob("purchaseMonitor", "0 */5 * * * *", async () => {
|
|
try {
|
|
const result = await prodQuery(
|
|
sqlQuery.query.replace(
|
|
"[interval]",
|
|
`${purchaseMonitor[0]?.value || "5"}`,
|
|
),
|
|
"Get release info",
|
|
);
|
|
|
|
log.debug(
|
|
{},
|
|
`There are ${result.data.length} pending to be updated from the last ${purchaseMonitor[0]?.value}`,
|
|
);
|
|
if (result.data.length) {
|
|
const convertedData = result.data.map((i) => ({
|
|
...i,
|
|
position: JSON.parse(i.position),
|
|
})) as NewAlplaPurchaseHistory;
|
|
|
|
const { data, error } = await tryCatch(
|
|
db.insert(alplaPurchaseHistory).values(convertedData).returning(),
|
|
);
|
|
|
|
if (data) {
|
|
log.debug(
|
|
{ data },
|
|
"New data was just added to alpla purchase history",
|
|
);
|
|
}
|
|
|
|
if (error) {
|
|
log.error(
|
|
{ error },
|
|
"There was an error adding alpla purchase history",
|
|
);
|
|
}
|
|
|
|
await delay(500);
|
|
}
|
|
} catch (e) {
|
|
console.error(
|
|
{ error: e },
|
|
"Error occurred while running the monitor job",
|
|
);
|
|
log.error({ error: e }, "Error occurred while running the monitor job");
|
|
|
|
return;
|
|
}
|
|
});
|
|
}
|
|
};
|