You've already forked obsidian-visualiser
79 lines
2.7 KiB
TypeScript
79 lines
2.7 KiB
TypeScript
import useDatabase from '~/composables/useDatabase';
|
|
import { hasPermissions } from "#shared/auth";
|
|
import { eq, sql } from "drizzle-orm";
|
|
import { projectContentTable, projectFilesTable } from "~/db/schema";
|
|
import { Project } from "~/schemas/project";
|
|
|
|
export default defineEventHandler(async (e) => {
|
|
const { user } = await getUserSession(e);
|
|
|
|
if(!user || !hasPermissions(user.permissions, ['admin', 'editor']))
|
|
{
|
|
throw createError({ statusCode: 401, statusText: 'Unauthorized' });
|
|
}
|
|
|
|
const body = await readValidatedBody(e, Project.safeParse);
|
|
|
|
if(!body.success)
|
|
{
|
|
throw body.error;
|
|
}
|
|
|
|
const db = useDatabase(), items = body.data, requested: string[] = [];
|
|
|
|
db.transaction((tx) => {
|
|
const data = tx.select({ id: projectFilesTable.id, timestamp: projectFilesTable.timestamp }).from(projectFilesTable).all();
|
|
const deleteOverview = tx.delete(projectFilesTable).where(eq(projectFilesTable.id, sql.placeholder('id'))).prepare();
|
|
const deleteContent = tx.delete(projectContentTable).where(eq(projectContentTable.id, sql.placeholder('id'))).prepare();
|
|
|
|
for(let i = 0; i < items.length; i++)
|
|
{
|
|
const submitted = items[i]!;
|
|
|
|
const index = data.findIndex(e => e.id === submitted.id);
|
|
|
|
if(index !== -1)
|
|
{
|
|
if(data[index]!.timestamp < new Date(submitted.timestamp))
|
|
{
|
|
requested.push(submitted.id);
|
|
continue;
|
|
}
|
|
|
|
data.splice(index, 1);
|
|
}
|
|
|
|
tx.insert(projectFilesTable).values({
|
|
id: submitted.id,
|
|
path: submitted.path,
|
|
owner: user.id,
|
|
title: submitted.title,
|
|
type: submitted.type,
|
|
navigable: submitted.navigable,
|
|
private: submitted.private,
|
|
order: submitted.order,
|
|
}).onConflictDoUpdate({
|
|
set: {
|
|
id: submitted.id,
|
|
path: submitted.path,
|
|
title: submitted.title,
|
|
type: submitted.type,
|
|
navigable: submitted.navigable,
|
|
private: submitted.private,
|
|
order: submitted.order,
|
|
timestamp: new Date(),
|
|
},
|
|
target: projectFilesTable.id,
|
|
}).run();
|
|
}
|
|
|
|
//Delete the remaining data has they have not been found in the new overview
|
|
for(let i = 0; i < data.length; i++)
|
|
{
|
|
deleteOverview.run({ id: data[i]!.id });
|
|
deleteContent.run({ id: data[i]!.id });
|
|
}
|
|
});
|
|
|
|
return requested;
|
|
}); |