Refactor: Remove SQL from Locals

This commit is contained in:
Donatas Kirda 2024-05-16 09:59:12 +03:00
parent 6e0e91b0ce
commit bc04506fe1
Signed by: bloodwiing
GPG Key ID: 63020D8D3F4A164F
9 changed files with 54 additions and 38 deletions

View File

@ -1,12 +1,7 @@
import { sql } from '$lib/db.server';
export const handle = async ({event, resolve}) => {
// https://github.com/porsager/postgres/issues/762
event.locals = {
sql: sql
};
const response = await resolve(event);
return response;
};

View File

@ -1,4 +1,5 @@
import { createCache } from '$lib/cache.server';
import { sql } from '$lib/db.server';
import { cacheUpdater, cachedMethod, refExtendCachedMethod } from './root';
const cache = createCache();
@ -30,7 +31,6 @@ function parseCategoryFromRow(row) {
const updateCategoryCache = cacheUpdater(cache);
/**
* @param {import('postgres').Sql} sql
* @param {number[] | undefined} user_ids
* @returns {Promise<Result<Category>>}
*/
@ -39,11 +39,10 @@ export const getCategoriesCached = cachedMethod(cache, getCategories);
export const getCategoriesCachedByRef = refExtendCachedMethod(getCategoriesCached);
/**
* @param {import('postgres').Sql} sql
* @param {number[] | undefined} category_ids
* @returns {Promise<Result<Category>>}
*/
export async function getCategories(sql, category_ids = undefined) {
export async function getCategories(category_ids = undefined) {
if (category_ids !== undefined && category_ids.length == 0) return new Map();
const filter = category_ids ? sql`WHERE id IN ${ sql(category_ids) }` : sql``;
@ -68,13 +67,11 @@ export async function getCategories(sql, category_ids = undefined) {
}
/**
*
* @param {import('postgres').Sql} sql
* @param {number} category_id
* @returns {Promise<Category | import('$types/error').Error>}
*/
export async function getCategoryCached(sql, category_id) {
const categories = await getCategoriesCached(sql, [category_id]);
export async function getCategoryCached(category_id) {
const categories = await getCategoriesCached([category_id]);
return categories.get(category_id) || {
error: true,

View File

@ -1,3 +1,4 @@
import { sql } from '$lib/db.server';
import { getUsersCachedByRef } from './user';
/**
@ -26,11 +27,10 @@ function parseCommentFromRow(author, row) {
}
/**
* @param {import('postgres').Sql} sql
* @param {number} post_id
* @returns {Promise<Comment[]>}
*/
export async function getCommentsForPost(sql, post_id) {
export async function getCommentsForPost(post_id) {
const query = sql`
SELECT id, author_id, latest_content, edit_count, parent_comment_id, created_date, likes, dislikes
FROM doki8902.message_comment
@ -38,7 +38,7 @@ export async function getCommentsForPost(sql, post_id) {
const comments = await query;
const users = await getUsersCachedByRef(sql, comments, c => c['author_id']);
const users = await getUsersCachedByRef(comments, c => c['author_id']);
/**
* @type {Comment[]}

View File

@ -1,3 +1,4 @@
import { sql } from '$lib/db.server';
import { getCategoriesCachedByRef, getCategoryCached } from './category';
import { getUser, getUsersCachedByRef } from './user';
@ -47,7 +48,6 @@ function parsePostFromRow(author, category, row, withMetrics = false) {
}
/**
* @param {import('postgres').Sql} sql
* @param {{
* category?: import('$types/base').Category | undefined,
* limit?: number,
@ -56,7 +56,7 @@ function parsePostFromRow(author, category, row, withMetrics = false) {
* }} opts
* @returns {Promise<Post[]>}
*/
export async function getPosts(sql, opts = {}) {
export async function getPosts(opts = {}) {
const {
category = undefined,
limit = 10,
@ -76,8 +76,8 @@ export async function getPosts(sql, opts = {}) {
const posts = await query;
const users = await getUsersCachedByRef(sql, posts, p => p['author_id']);
const categories = await getCategoriesCachedByRef(sql, posts, p => p['category_id']);
const users = await getUsersCachedByRef(posts, p => p['author_id']);
const categories = await getCategoriesCachedByRef(posts, p => p['category_id']);
/**
* @type {Post[]}
@ -92,14 +92,13 @@ export async function getPosts(sql, opts = {}) {
/**
*
* @param {import('postgres').Sql} sql
* @param {number} post_id
* @param {{
* withMetrics?: boolean
* }} opts
* @returns {Promise<Post | import('$types/error').Error>}
*/
export async function getPost(sql, post_id, opts = {}) {
export async function getPost(post_id, opts = {}) {
const {
withMetrics = false
} = opts;
@ -120,7 +119,7 @@ export async function getPost(sql, post_id, opts = {}) {
};
}
const user_guess = await getUser(sql, post['author_id']);
const user_guess = await getUser(post['author_id']);
/**
* @type {import('$types/base').User | null}
*/

View File

@ -15,11 +15,11 @@ export const cacheUpdater = (cache) => {
/**
* @template T
* @param {import('node-cache')} cache
* @param {function(import('postgres').Sql, number[]): Promise<import('$types/base').Result<T>>} method
* @returns {function(import('postgres').Sql, number[]): Promise<import('$types/base').Result<T>>}
* @param {function(number[]): Promise<import('$types/base').Result<T>>} method
* @returns {function(number[]): Promise<import('$types/base').Result<T>>}
*/
export const cachedMethod = (cache, method) => {
return async function(sql, ids) {
return async function(ids) {
/**
* @type {import('$types/base').Result<T>}
*/
@ -39,7 +39,7 @@ export const cachedMethod = (cache, method) => {
missing.push(id);
});
const remaining = await method(sql, missing);
const remaining = await method(missing);
return new Map([...results, ...remaining]);
};
@ -47,11 +47,11 @@ export const cachedMethod = (cache, method) => {
/**
* @template T
* @param {function(import('postgres').Sql, number[]): Promise<import('$types/base').Result<T>>} cachedMethod
* @returns {function(import('postgres').Sql, import('postgres').RowList<import('postgres').Row[]>, function(import('postgres').Row): number): Promise<import('$types/base').Result<T>>}
* @param {function(number[]): Promise<import('$types/base').Result<T>>} cachedMethod
* @returns {function(import('postgres').RowList<import('postgres').Row[]>, function(import('postgres').Row): number): Promise<import('$types/base').Result<T>>}
*/
export const refExtendCachedMethod = (cachedMethod) => {
return async function(sql, rows, getRef) {
return await cachedMethod(sql, rows.map(r => getRef(r)));
return async function(rows, getRef) {
return await cachedMethod(rows.map(r => getRef(r)));
}
}

View File

@ -1,4 +1,5 @@
import { createCache } from '$lib/cache.server';
import { genSalt } from 'bcrypt';
import { cacheUpdater, cachedMethod, refExtendCachedMethod } from './root';
const cache = createCache();
@ -79,3 +80,27 @@ export async function getUser(sql, user_id) {
msg: `Could not find user of ID ${user_id}`
};
}
/**
* @param {import('postgres').Sql} sql
* @param {string} username
* @param {string} password
* @returns {Promise<string | import('$types/error').Error>}
*/
export async function registerUser(sql, username, password) {
// const users = await getUsers(sql, [user_id]);
// return users.get(user_id) || {
// error: true,
// msg: `Could not find user of ID ${user_id}`
// };
const salt = await genSalt(10);
console.log(salt);
// const hash =
// const insert = sql`
// INSERT INTO doki8902.user (username, password)
// VALUES (${ username }, ${ hash })`
}

View File

@ -2,13 +2,13 @@ import { getPost, getPosts } from '$lib/server/db/post';
/** @type {import('./$types').PageServerLoad} */
export async function load({ locals, url }) {
const result = await getPosts(locals.sql);
export async function load({ url }) {
const result = await getPosts();
const glance = url.searchParams.get('glance');
const glanceID = glance ? parseInt(glance) : null
const glancePost = glanceID ? await getPost(locals.sql, glanceID, { withMetrics: true }) : null;
const glancePost = glanceID ? await getPost(glanceID, { withMetrics: true }) : null;
return {
posts: result,

View File

@ -4,16 +4,16 @@ import { getIdFromName } from "$lib/util";
import { error } from "@sveltejs/kit";
/** @type {import("@sveltejs/kit").ServerLoad} */
export async function load({ params, locals }) {
export async function load({ params }) {
const post_id = getIdFromName(params.name);
if (post_id === null) {
error(404, `No Post of ID ${params.name}`);
}
const post = await getPost(locals.sql, post_id);
const post = await getPost(post_id);
const comments = await getCommentsForPost(locals.sql, post_id);
const comments = await getCommentsForPost(post_id);
return {
post: post,

View File

@ -3,14 +3,14 @@ import { getIdFromName } from "$lib/util";
import { error } from "@sveltejs/kit";
/** @type {import("@sveltejs/kit").ServerLoad} */
export async function load({ locals, params }) {
export async function load({ params }) {
const user_id = getIdFromName(params.name);
if (user_id === null) {
return error(404, `Invalid Name ${params.name}`);
}
const user = await getUser(locals.sql, user_id);
const user = await getUser(user_id);
if ('error' in user) {
return error(404, `No User of ID ${user_id}`);