Combined functions, Changed some items

This commit is contained in:
Esad Mustafoski
2024-11-07 19:29:35 +01:00
parent f45945474d
commit 7a6152be51
6 changed files with 143 additions and 70 deletions

View File

@@ -14,22 +14,22 @@ const _dirname: string = dirname(fromFileUrl(import.meta.url));
const dbPath: string = join(_dirname, "../database/esp-projekt.sqlite"); const dbPath: string = join(_dirname, "../database/esp-projekt.sqlite");
const db = new DB(dbPath); const db = new DB(dbPath);
db.execute(` export function createDatabase(): void {
db.execute(`
CREATE TABLE IF NOT EXISTS accounts ( CREATE TABLE IF NOT EXISTS accounts (
user_id INTEGER PRIMARY KEY AUTOINCREMENT, uuid INTEGER PRIMARY KEY AUTOINCREMENT,
user_group TEXT, user_group TEXT,
bio TEXT, user_bio TEXT,
displayname TEXT, user_displayname TEXT,
username TEXT, user_username TEXT,
user_email TEXT, user_e-mail TEXT,
password TEXT, password TEXT,
firstname TEXT, firstname TEXT,
surname TEXT, surname TEXT,
account_created TEXT, account_created TEXT,
blocked_users TEXT, followers ANY,
followers TEXT, following ANY,
following TEXT, contacts ANY
contacts TEXT
) )
CREATE TABLE IF NOT EXISTS posts ( CREATE TABLE IF NOT EXISTS posts (
@@ -42,17 +42,19 @@ db.execute(`
) )
CREATE TABLE IF NOT EXISTS comments ( CREATE TABLE IF NOT EXISTS comments (
comment_id INTEGER PRIMARY KEY AUTOINCREMENT, commentd_id INTEGER PRIMARY KEY AUTOINCREMENT,
post_id INTEGER, post_id INTEGER,
user_id INTEGER, author_user_id INTEGER,
created_at TEXT, date_created_at TEXT,
comment_text TEXT text TEXT,
likes INTEGER
) )
`); `);
}
// Sample data generated using online generators // Sample data generated using online generators
export function insertSampleData(): void { export function insertSampleData(): void {
db.query(`INSERT INTO accounts (user_group, bio, displayname, username, user_email, password, firstname, surname, account_created, blocked_users, followers, following, contacts) VALUES db.query(`INSERT INTO accounts (user_group, user_bio, user_displayname, user_username, user_email, password, firstname, surname, account_created, followers, following, contacts) VALUES
('admin', 'Admin bio', 'Admin User', 'admin', 'admin@example.com', 'hashedpass1', 'Admin', 'User', '2024-01-01', '[]', '[]', '[]', '[]'), ('admin', 'Admin bio', 'Admin User', 'admin', 'admin@example.com', 'hashedpass1', 'Admin', 'User', '2024-01-01', '[]', '[]', '[]', '[]'),
('user', 'I love coding!', 'John Dev', 'johndev', 'john@example.com', 'hashedpass2', 'John', 'Smith', '2024-01-02', '[]', '[3,4]', '[1,2]', '[]'), ('user', 'I love coding!', 'John Dev', 'johndev', 'john@example.com', 'hashedpass2', 'John', 'Smith', '2024-01-02', '[]', '[3,4]', '[1,2]', '[]'),
('user', 'Photography enthusiast', 'Alice', 'alice_photo', 'alice@example.com', 'hashedpass3', 'Alice', 'Johnson', '2024-01-03', '[5]', '[1]', '[2]', '[]') ('user', 'Photography enthusiast', 'Alice', 'alice_photo', 'alice@example.com', 'hashedpass3', 'Alice', 'Johnson', '2024-01-03', '[5]', '[1]', '[2]', '[]')
@@ -65,11 +67,11 @@ export function insertSampleData(): void {
(3, '2024-01-16 14:20:00', 'Posted my new photo collection', 15, 4) (3, '2024-01-16 14:20:00', 'Posted my new photo collection', 15, 4)
`); `);
db.query(`INSERT INTO comments (post_id, user_id, created_at, comment_text) VALUES db.query(`INSERT INTO comments (post_id, author_user_id, date_created_at, text, likes) VALUES
(1, 2, '2024-01-15 10:05:00', 'Great post!'), (1, 2, '2024-01-15 10:05:00', 'Great post!', 3),
(1, 3, '2024-01-15 10:10:00', 'Very informative'), (1, 3, '2024-01-15 10:10:00', 'Very informative', 2),
(2, 3, '2024-01-15 11:35:00', 'Nice feature'), (2, 3, '2024-01-15 11:35:00', 'Nice feature', 4),
(3, 1, '2024-01-16 09:20:00', 'TypeScript is awesome'), (3, 1, '2024-01-16 09:20:00', 'TypeScript is awesome', 5),
(4, 2, '2024-01-16 14:25:00', 'Beautiful photos!') (4, 2, '2024-01-16 14:25:00', 'Beautiful photos!', 6)
`); `);
}; };

Binary file not shown.

View File

@@ -8,6 +8,7 @@
// +++ IMPORTS ------------------------------------------------------ // // +++ IMPORTS ------------------------------------------------------ //
import { DB, Row } from "https://deno.land/x/sqlite/mod.ts"; import { DB, Row } from "https://deno.land/x/sqlite/mod.ts";
import { dirname, fromFileUrl, join } from "https://deno.land/std/path/mod.ts"; import { dirname, fromFileUrl, join } from "https://deno.land/std/path/mod.ts";
import * as db_create from "./create_db.ts";
// +++ VARIABLES ---------------------------------------------------- // // +++ VARIABLES ---------------------------------------------------- //
// __dirname Is never getting used again, It's only needed because the DB Import // __dirname Is never getting used again, It's only needed because the DB Import
@@ -57,6 +58,14 @@ interface Comments {
// +++ FUNCTIONS---------------------------------------------------- // // +++ FUNCTIONS---------------------------------------------------- //
function insertSamples(): void {
db_create.insertSampleData();
}
function createDatabaseIfNotExist(): void {
db_create.createDatabase();
}
/** /**
* @param user_uuid The UUID of the User to get the Posts for. Not required * @param user_uuid The UUID of the User to get the Posts for. Not required
* @description If no user_uuid is provided, all Posts will be returned * @description If no user_uuid is provided, all Posts will be returned
@@ -67,6 +76,7 @@ async function getPostsFromDB(user_uuid?: string): Promise<Post[]> {
const data_result: Array<Post> = []; const data_result: Array<Post> = [];
let rows: Row[]; let rows: Row[];
try {
try { try {
if (user_uuid === undefined) { if (user_uuid === undefined) {
rows = await db.query(`SELECT * FROM posts`); rows = await db.query(`SELECT * FROM posts`);
@@ -75,6 +85,10 @@ async function getPostsFromDB(user_uuid?: string): Promise<Post[]> {
`SELECT * FROM posts WHERE user_id = ${user_uuid}`, `SELECT * FROM posts WHERE user_id = ${user_uuid}`,
); );
} }
} catch (error) {
console.error("Error fetching posts", error, "User UUID:", user_uuid);
return [];
}
for (const row of rows) { for (const row of rows) {
const [ const [
@@ -229,30 +243,80 @@ async function getAllUserInfoByID(user_id: number) {
const data_result_post: Array<Post> = []; const data_result_post: Array<Post> = [];
const data_result_comments: Array<Comments> = []; const data_result_comments: Array<Comments> = [];
let rowsAccount: Row[] = [];
let rowsPost: Row[] = [];
let rowsComments: Row[] = [];
try { try {
const [rowsAccount, rowsPost, rowsComments] = await Promise.all([ const [rowsAccount, rowsPost, rowsComments] = await Promise.all([
db.query('SELECT * FROM accounts WHERE uuid = ?', [user_id]), db.query("SELECT * FROM accounts WHERE uuid = ?", [user_id]),
db.query('SELECT * FROM posts WHERE uuid = ?', [user_id]), db.query("SELECT * FROM posts WHERE uuid = ?", [user_id]),
db.query('SELECT * FROM comments WHERE uuid = ?', [user_id]) db.query("SELECT * FROM comments WHERE uuid = ?", [user_id]),
]); ]);
for (const row in rowsAccount) {
const [user_id,user_group,bio,displayname,username,user_email,password,
firstname,surname,account_created,blocked_users,followers,following,
contacts,
] = row;
data_result_account.push({
user_id: Number(user_id),
user_group: String(user_group),
bio: String(bio),
displayname: String(displayname),
username: String(username),
user_email: String(user_email),
password: String(password),
firstname: String(firstname),
surname: String(surname),
account_created: String(account_created),
blocked_users: String(blocked_users),
followers: String(followers),
following: String(following),
contacts: String(contacts),
});
}
for (const row in rowsPost) {
const [
posts_uuid,
user_id,
created_at,
post_text,
likes,
comments,
] = row;
data_result_post.push({
posts_uuid: Number(posts_uuid),
user_id: Number(user_id),
created_at: String(created_at),
post_text: String(post_text),
likes: Number(likes),
comments: Number(comments),
});
}
for (const row in rowsComments) {
const [
comment_id,
post_id,
author_user_id,
date_created_at,
text,
likes,
] = row;
data_result_comments.push({
comment_id: Number(comment_id),
post_id: Number(post_id),
author_user_id: Number(author_user_id),
date_created_at: String(date_created_at),
text: String(text),
likes: Number(likes),
});
}
} catch (error) { } catch (error) {
console.error(` console.error(`Failed to get User Info ${error}`);
Failed to get User Info ${error}
rowsAccount: ${rowsAccount}
rowsPost: ${rowsPost}
rowsComments: ${rowsComments}
`);
return []; return [];
} }
return { data_result_account, data_result_comments, data_result_post }; const result = { data_result_account, data_result_comments, data_result_post };
return result;
} }
/** /**
@@ -264,16 +328,18 @@ function filterForImagePosts(posts_to_filter: Array<any>) {
return []; return [];
} }
function filterForVideoPosts() { function filterForVideoPosts(posts_to_filter: Array<any>) {
return []; return [];
} }
function filterForTextPosts() { function filterForTextPosts(posts_to_filter: Array<any>) {
return []; return [];
} }
// Exporting all functions as this is a module // Exporting all functions as this is a module
export { export {
createDatabaseIfNotExist,
insertSamples,
countPosts, countPosts,
filterForImagePosts, filterForImagePosts,
filterForTextPosts, filterForTextPosts,

View File

@@ -1,3 +1,5 @@
/// <reference types="vite/client" />
import { createRouter, createWebHistory } from "vue-router"; import { createRouter, createWebHistory } from "vue-router";
// Vue components imported here. // Vue components imported here.

View File

@@ -13,6 +13,9 @@ import { app } from "../api/main.ts";
// +++ TESTS ------------------------------------------------------- // // +++ TESTS ------------------------------------------------------- //
Deno.test("GET /api returns testAPIPoint", async () => { Deno.test("GET /api returns testAPIPoint", async () => {
const request = await superoak(app); const request = await superoak(app);
await request.get("/api").expect(200).expect("testAPIPoint"); await request
.get("/api")
.timeout(5000) // 5 seconds timeout
.expect(200)
.expect("testAPIPoint");
}); });

View File

@@ -72,12 +72,12 @@ Deno.test("filterForImagePosts returns array", () => {
}); });
Deno.test("filterForVideoPosts returns array", () => { Deno.test("filterForVideoPosts returns array", () => {
const result = db_utils.filterForVideoPosts(); const result = db_utils.filterForVideoPosts([]);
assert(Array.isArray(result), "Should return an array"); assert(Array.isArray(result), "Should return an array");
}); });
Deno.test("filterForTextPosts returns array", () => { Deno.test("filterForTextPosts returns array", () => {
const result = db_utils.filterForTextPosts(); const result = db_utils.filterForTextPosts([]);
assert(Array.isArray(result), "Should return an array"); assert(Array.isArray(result), "Should return an array");
}); });
@@ -104,13 +104,13 @@ Deno.test("getCommentsFromDB handles invalid comment_id", () => {
}); });
// User Info Tests // User Info Tests
Deno.test("getUserInfoByID handles invalid user_id", () => { Deno.test("getUserInfoByID handles invalid user_id", async () => {
const result = db_utils.getAllUserInfoByID(-1); const result = await db_utils.getAllUserInfoByID(-1);
assertEquals(result, undefined, "Should handle invalid user_id"); assertEquals(result, [], "Should handle invalid user_id");
}); });
Deno.test("getPostsFromDB handles invalid user_id", async () => { Deno.test("getPostsFromDB handles invalid user_id", async () => {
const result = await db_utils.getPostsFromDB("invalid"); const result = await db_utils.getPostsFromDB("-1");
assertEquals(result, [], "Should handle invalid user_id"); assertEquals(result, [], "Should handle invalid user_id");
}); });