63 lines
1.6 KiB
TypeScript
63 lines
1.6 KiB
TypeScript
import { mkdir, readdir, rm } from 'node:fs/promises';
|
|
import { join } from 'node:path';
|
|
import { createRouter } from '@@/create-router';
|
|
import {
|
|
getDirs,
|
|
migrateFromState,
|
|
migrateHomepageToScreens,
|
|
readAllWorkspacesState,
|
|
resolveKey,
|
|
writeJsonFile,
|
|
} from './utils';
|
|
|
|
export const workspacesRouter = createRouter();
|
|
|
|
// GET /workspaces
|
|
workspacesRouter.get('/', async (ctx) => {
|
|
const email = ctx.get('user').email;
|
|
const dirs = getDirs(email);
|
|
|
|
const dirFile = Bun.file(join(dirs.wsDir, 'index.json'));
|
|
if (!(await dirFile.exists())) {
|
|
await migrateFromState(email, dirs);
|
|
}
|
|
|
|
await migrateHomepageToScreens(dirs, email);
|
|
|
|
const state = await readAllWorkspacesState(dirs);
|
|
return ctx.json(state);
|
|
});
|
|
|
|
// PATCH /workspaces
|
|
workspacesRouter.patch('/', async (ctx) => {
|
|
const email = ctx.get('user').email;
|
|
const body = ctx.get('body') as Record<string, unknown>;
|
|
const dirs = getDirs(email);
|
|
|
|
await mkdir(dirs.wsDir, { recursive: true });
|
|
|
|
for (const [key, value] of Object.entries(body)) {
|
|
const mapping = resolveKey(dirs, key);
|
|
if (!mapping) continue;
|
|
|
|
if (value === null) {
|
|
try {
|
|
await rm(mapping.file, { force: true });
|
|
if (mapping.dir) {
|
|
const remaining = await readdir(mapping.dir);
|
|
if (remaining.length === 0) await rm(mapping.dir, { recursive: true, force: true });
|
|
}
|
|
} catch {
|
|
// ignore
|
|
}
|
|
continue;
|
|
}
|
|
|
|
if (mapping.dir) await mkdir(mapping.dir, { recursive: true });
|
|
await writeJsonFile(mapping.file, value);
|
|
}
|
|
|
|
const state = await readAllWorkspacesState(dirs);
|
|
return ctx.json(state);
|
|
});
|