35 lines
1.3 KiB
TypeScript
35 lines
1.3 KiB
TypeScript
import { Product } from 'ssn';
|
|
import * as database from './database';
|
|
import products from './products';
|
|
import writeLog from '../logger/writeLog';
|
|
import createStatement from './createStatement';
|
|
import IDatabaseRow from '../interfaces/IDatabaseRow';
|
|
|
|
const state: any = {};
|
|
|
|
export async function init() {
|
|
await database.init();
|
|
|
|
//Only create table if it does not exist yet
|
|
const createIfNotExists = createStatement.replace(/^CREATE TABLE/, 'CREATE TABLE IF NOT EXISTS');
|
|
await database.query(createIfNotExists);
|
|
|
|
const { results: existingRows }: { results: IDatabaseRow[]} = await database.query('SELECT * FROM ssn_versions');
|
|
|
|
existingRows.forEach(function(row: IDatabaseRow) {
|
|
if (!products.includes(row.product)) {
|
|
writeLog(`Product ${row.product} in database table is invalid.`);
|
|
return;
|
|
}
|
|
|
|
state[row.product] = { http: row.http, manifest: row.manifest };
|
|
});
|
|
|
|
//If row does not exist, INSERT into table
|
|
await Promise.all(products.filter((product) => state[product] === undefined).map(function(product) {
|
|
state[product] = { http: -1, manifest: -1 };
|
|
return database.query(`INSERT INTO \`ssn_versions\` (\`product\`, \`manifest\`, \`http\`) VALUES ('${product.replace(/'/g, '\\\'')}', '-1', '-1');`)
|
|
}));
|
|
|
|
return state;
|
|
}
|