From fa40db066287866fb83b97159f4969aaec0fefb0 Mon Sep 17 00:00:00 2001 From: Josh Moore Date: Sun, 16 Jul 2023 19:23:03 -0600 Subject: [PATCH] feat: added initial data file management (no put/get/etc yet) --- backend/app.ts | 4 +++ backend/data.ts | 65 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+) create mode 100644 backend/data.ts diff --git a/backend/app.ts b/backend/app.ts index ea8817d..9f31a09 100644 --- a/backend/app.ts +++ b/backend/app.ts @@ -4,6 +4,7 @@ import { path, isProd } from '@tycrek/joint'; import { epcss } from '@tycrek/express-postcss'; import tailwindcss from 'tailwindcss'; import { log } from './log'; +import { ensureFiles } from './data'; import { UserConfig } from './UserConfig'; import { ServerConfiguration } from 'ass'; @@ -27,6 +28,9 @@ async function main() { const pkg = await fs.readJson(path.join('package.json')) as { name: string, version: string }; log.blank().info(pkg.name, pkg.version).blank(); + // Ensure data files exist + await ensureFiles(); + // Set default server configuration const serverConfig: ServerConfiguration = { host: '0.0.0.0', diff --git a/backend/data.ts b/backend/data.ts new file mode 100644 index 0000000..c549279 --- /dev/null +++ b/backend/data.ts @@ -0,0 +1,65 @@ +import fs from 'fs-extra'; +import { path } from '@tycrek/joint'; +import { nanoid } from 'nanoid'; +import { log } from './log'; +import { AssFile, AssUser, NID, FilesSchema, UsersSchema } from 'ass'; + +/** + * Switcher type for exported functions + */ +type DataSector = 'files' | 'users'; + +/** + * Absolute filepaths for JSON data files + */ +const PATHS = { + files: path.join('.ass-data/files.json'), + users: path.join('.ass-data/users.json') +}; + +/** + * Creates a JSON file with a given empty data template + */ +const createEmptyJson = (filepath: string, emptyData: any): Promise => new Promise(async (resolve, reject) => { + try { + if (!(await fs.pathExists(filepath))) { + await fs.ensureFile(filepath); + await fs.writeJson(filepath, emptyData, { spaces: '\t' }); + } + resolve(void 0); + } catch (err) { + reject(err); + } +}); + +/** + * Ensures the data files exist and creates them if required + */ +export const ensureFiles = (): Promise => new Promise(async (resolve, reject) => { + log.debug('Checking data files'); + + try { + // Create data directory + await fs.ensureDir(path.join('.ass-data')); + + // * Default files.json + await createEmptyJson(PATHS.files, { + files: [], + meta: {} + } as FilesSchema); + + // * Default users.json + await createEmptyJson(PATHS.users, { + tokens: [], + users: [], + cliKey: nanoid(32), + meta: {} + } as UsersSchema); + + log.debug('Data files exist'); + resolve(); + } catch (err) { + log.error('Failed to verify existence of data files'); + reject(err); + } +});