fix: Fix corrupt database, Add soundcloud and spotify embeds
This commit is contained in:
@@ -1,4 +1,6 @@
|
||||
import { randomBytes } from 'crypto';
|
||||
import fs from 'fs';
|
||||
import fsp from 'fs/promises';
|
||||
import path from 'path';
|
||||
import { DataSource } from 'typeorm';
|
||||
import {
|
||||
@@ -101,6 +103,23 @@ function resolveSqlJsConfig(): { locateFile: (file: string) => string } {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Write the database to disk atomically: write a temp file first,
|
||||
* then rename it over the real file. rename() is atomic on the same
|
||||
* filesystem, so a crash mid-write can never leave a half-written DB.
|
||||
*/
|
||||
async function atomicSave(data: Uint8Array): Promise<void> {
|
||||
const tmpPath = DB_FILE + '.tmp-' + randomBytes(6).toString('hex');
|
||||
|
||||
try {
|
||||
await fsp.writeFile(tmpPath, Buffer.from(data));
|
||||
await fsp.rename(tmpPath, DB_FILE);
|
||||
} catch (err) {
|
||||
await fsp.unlink(tmpPath).catch(() => {});
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
export function getDataSource(): DataSource {
|
||||
if (!applicationDataSource?.isInitialized) {
|
||||
throw new Error('DataSource not initialised');
|
||||
@@ -136,7 +155,7 @@ export async function initDatabase(): Promise<void> {
|
||||
synchronize: process.env.DB_SYNCHRONIZE === 'true',
|
||||
logging: false,
|
||||
autoSave: true,
|
||||
location: DB_FILE,
|
||||
autoSaveCallback: atomicSave,
|
||||
sqlJsConfig: resolveSqlJsConfig()
|
||||
});
|
||||
} catch (error) {
|
||||
|
||||
Reference in New Issue
Block a user