Compare commits

...

2 Commits

Author SHA1 Message Date
7312ab632c refactoring 2024-07-18 16:14:34 +02:00
e0377aeb00 fixed issue 2024-07-18 15:48:05 +02:00
3 changed files with 157 additions and 169 deletions

View File

@ -141,19 +141,9 @@ export async function tryCreateAttachment(request: Request) {
export async function tryFetchAttachments(request: Request) { export async function tryFetchAttachments(request: Request) {
await Post.sync(); await Post.sync();
const foundPosts = await Post.findAll({ const foundAttachments = await Attachment.findAll();
include: [
{
association: Post.associations.user,
attributes: { exclude: ["password", "createdAt", "updatedAt"] },
},
{
association: Post.associations.postTags,
},
],
});
return new Response(JSON.stringify(foundPosts), { status: 200 }); return new Response(JSON.stringify(foundAttachments), { status: 200 });
} }
export async function GET(request: Request) { export async function GET(request: Request) {

View File

@ -4,24 +4,24 @@ import { cookies } from "next/headers";
import { APIError } from "@/util/api/error"; import { APIError } from "@/util/api/error";
import { import {
Attachment, Attachment,
Auth, Auth,
Bucket, Bucket,
DBState, DBState,
Post, Post,
PostTag, PostTag,
Project, Project,
Tag, Tag,
User, User,
UserPerms, UserPerms,
dbSync, dbSync,
sequelize, sequelize,
} from "@/models"; } from "@/models";
import Sequelize, { CreationAttributes, DataTypes } from "@sequelize/core"; import Sequelize, { CreationAttributes, DataTypes } from "@sequelize/core";
import { import {
SqliteColumnsDescription, SqliteColumnsDescription,
SqliteDialect, SqliteDialect,
SqliteQueryInterface, SqliteQueryInterface,
} from "@sequelize/sqlite3"; } from "@sequelize/sqlite3";
import { hashpassword } from "@/util/auth"; import { hashpassword } from "@/util/auth";
import { copyFile, readFileSync } from "fs"; import { copyFile, readFileSync } from "fs";
@ -30,160 +30,158 @@ import { UUID } from "crypto";
import { runApiAction } from "@/util/api"; import { runApiAction } from "@/util/api";
async function seedUsers(qif: SqliteQueryInterface<SqliteDialect>) { async function seedUsers(qif: SqliteQueryInterface<SqliteDialect>) {
const fp = path.resolve("./db/seed/users.json"); const fp = path.resolve("./db/seed/users.json");
const json: { users: CreationAttributes<User>[] } = JSON.parse( const json: { users: CreationAttributes<User>[] } = JSON.parse(
Buffer.from(readFileSync(fp).valueOf()).toString() Buffer.from(readFileSync(fp).valueOf()).toString()
); );
const users = json.users.map(async (user) => { const users = json.users.map(async (user) => {
user.password = await hashpassword(user.password); user.password = await hashpassword(user.password);
return user; return user;
}); });
const dbUsers = await User.bulkCreate(await Promise.all(users), { const dbUsers = await User.bulkCreate(await Promise.all(users), {
include: User.associations.perms, include: User.associations.perms,
}); });
} }
async function seedPosts(qif: SqliteQueryInterface<SqliteDialect>) { async function seedPosts(qif: SqliteQueryInterface<SqliteDialect>) {
const fp = path.resolve("./db/seed/posts.json"); const fp = path.resolve("./db/seed/posts.json");
const json: { users: CreationAttributes<User>[] } = JSON.parse( const json: { users: CreationAttributes<User>[] } = JSON.parse(
Buffer.from(readFileSync(fp).valueOf()).toString() Buffer.from(readFileSync(fp).valueOf()).toString()
); );
const projects = [ const projects = [
{ {
name: "Blog", name: "Blog",
readableIdentifier: "blog", readableIdentifier: "blog",
posts: [ posts: [
{ {
title: "Test Post", title: "Test Post",
content: content:
"# Hello <ExampleComponent />\nthis is some **test** markdown and we make some edits\n![](/attachment/788dfc19-55ba-482c-8124-277702296dfb/FB_IMG_1716665756868.jpg)", "# Hello <ExampleComponent />\nthis is some **test** markdown and we make some edits\n![](/attachment/788dfc19-55ba-482c-8124-277702296dfb/FB_IMG_1716665756868.jpg)",
description: "A new post to test the blog system", description: "A new post to test the blog system",
project_id: 1, project_id: 1,
user_id: 1, user_id: 1,
buckets: [ buckets: [
{ {
id: "788dfc19-55ba-482c-8124-277702296dfb", id: "788dfc19-55ba-482c-8124-277702296dfb",
attachments: [ attachments: [
{ {
filename: "FB_IMG_1716665756868.jpg", filename: "FB_IMG_1716665756868.jpg",
}, },
], ],
}, },
], ],
}, },
], ],
}, },
]; ];
projects.map((project) => { projects.map((project) => {
Project.create({ Project.create({
name: project.name, name: project.name,
readableIdentifier: project.readableIdentifier, readableIdentifier: project.readableIdentifier,
}); });
project.posts.map(async (post) => { project.posts.map(async (post) => {
const pst = await Post.create({ const pst = await Post.create({
title: post.title, title: post.title,
content: post.content, content: post.content,
description: post.description, description: post.description,
project_id: post.project_id, project_id: post.project_id,
user_id: post.user_id, user_id: post.user_id,
}); });
post.buckets.map(async (bucket) => { post.buckets.map(async (bucket) => {
pst.createBucket({ id: bucket.id as UUID }); pst.createBucket({ id: bucket.id as UUID });
bucket.attachments.map((attachment) => { bucket.attachments.map((attachment) => {
Attachment.create({ Attachment.create({
bucket_id: bucket.id as UUID, bucket_id: bucket.id as UUID,
filename: attachment.filename, filename: attachment.filename,
}).then((a) => { }).then((a) => {
copyFile( copyFile(
path.resolve(".", "db", "seed", "post", a.filename), path.resolve(".", "db", "seed", "post", a.filename),
path.resolve(".", "bucket", bucket.id, a.filename), path.resolve(".", "bucket", bucket.id, a.filename),
() => {} () => {}
); );
}); });
}); });
}); });
}); });
}); });
const project = await Project.findOne({ const project = await Project.findOne({
where: { where: {
readableIdentifier: "blog", readableIdentifier: "blog",
}, },
}).then((e) => }).then(
e (project) =>
? e project ||
: Project.create({ Project.create({
name: "General Blog", name: "General Blog",
readableIdentifier: "blog", readableIdentifier: "blog",
}) })
); );
} }
async function seedDatabase(qif: SqliteQueryInterface<SqliteDialect>) { async function seedDatabase(qif: SqliteQueryInterface<SqliteDialect>) {
await seedUsers(qif); await seedUsers(qif);
await seedPosts(qif); await seedPosts(qif);
// await Post.create({ // await Post.create({
// title: 'Test Post', // title: 'Test Post',
// content: ` // content: `
// # Hello <ExampleComponent /> // # Hello <ExampleComponent />
// this is some **test** markdown // this is some **test** markdown
// `, // `,
// project_id: project.id, // project_id: project.id,
// user_id: user.id // user_id: user.id
// }) // })
// await Post.create({ // await Post.create({
// title: 'Test Post 2', // title: 'Test Post 2',
// content: ` // content: `
// # Hello <ExampleComponent /> // # Hello <ExampleComponent />
// this is amother post with some **test** markdown // this is amother post with some **test** markdown
// `, // `,
// project_id: project.id, // project_id: project.id,
// user_id: user.id // user_id: user.id
// }) // })
} }
export async function GET(request: Request) { export async function GET(request: Request) {
runApiAction(async (request) => { runApiAction(async (request) => {
await dbSync; await dbSync;
const queryInterface = sequelize.queryInterface; const queryInterface = sequelize.queryInterface;
const version = (await DBState.findAll()) const version = (await DBState.findAll())
.sort((a, b) => (a.version > b.version ? 1 : -1)) .sort((a, b) => (a.version > b.version ? 1 : -1))
.map((a) => a.version)[0]; .map((a) => a.version)[0];
switch (version) { switch (version) {
case 1: case 1:
break; break;
default: default:
seedDatabase(queryInterface); seedDatabase(queryInterface);
const postsRows: SqliteColumnsDescription = await queryInterface const postsRows: SqliteColumnsDescription = await queryInterface
.describeTable(Post.table.tableName) .describeTable(Post.table.tableName)
.then((t) => t); .then((t) => t);
if (!postsRows["project_id"]) if (!postsRows["project_id"])
queryInterface.addColumn("Posts", "project_id", { queryInterface.addColumn("Posts", "project_id", {
type: DataTypes.INTEGER, type: DataTypes.INTEGER,
acceptsNull: () => false, acceptsNull: () => false,
defaultValue: 1, defaultValue: 1,
}); });
break; break;
} }
return new Response( return new Response(
JSON.stringify({ JSON.stringify({
test: await queryInterface test: await queryInterface.describeTable("Posts").then((t) => t),
.describeTable("Posts") }),
.then((t) => t), {
}), status: 200,
{ headers: {
status: 200, "Content-Type": "text/JSON",
headers: { },
"Content-Type": "text/JSON", }
}, );
} }, request);
);
}, request);
} }

View File

@ -38,9 +38,9 @@ export async function getPostsWithBucketsAndProject(): Promise<ActionResult<GetP
{association: Post.associations.project}], {association: Post.associations.project}],
nest: false nest: false
}); });
return {result:JSON.parse(JSON.stringify(posts.map((e:Post)=>{ return {result:posts.map((post:Post)=>{
return inspect(e) return JSON.parse(JSON.stringify(post))
})))}; })};
} }
export async function getPosts(): Promise<ActionResult<Attributes<Post>[]>> { export async function getPosts(): Promise<ActionResult<Attributes<Post>[]>> {