55 lines
1.5 KiB
TypeScript
55 lines
1.5 KiB
TypeScript
import db from "./db.js";
|
|
import { z } from "zod";
|
|
|
|
export const slugRegex = /^[a-zA-Z0-9_-]+$/;
|
|
|
|
export const zArticle = z.object({
|
|
id: z.number().min(0),
|
|
title: z.string().min(1),
|
|
slug: z.string().regex(slugRegex).min(3).max(100),
|
|
file: z.string().regex(/^[a-zA-Z0-9_-]+\.md$/),
|
|
users_id: z.number().min(0),
|
|
deleted: z.boolean(),
|
|
created_at: z.date(),
|
|
updated_at: z.union([z.date(), z.null()])
|
|
});
|
|
|
|
export type Article = z.infer<typeof zArticle>;
|
|
|
|
export const getBySlug = async (slug: string): Promise<Article | null> => {
|
|
return db<Article>("articles")
|
|
.where("slug", slug)
|
|
.first()
|
|
.then((rec) => !!rec ? rec : null)
|
|
};
|
|
|
|
export const getById = async (articleId: number): Promise<Article | null> => {
|
|
return db<Article>("articles")
|
|
.where("id", articleId)
|
|
.first()
|
|
.then((rec) => !!rec ? rec : null)
|
|
};
|
|
|
|
export const getByUserId = async (userId: number): Promise<Article[]> =>
|
|
db<Article>("articles")
|
|
.where("users_id", userId)
|
|
.orderBy("created_at", "desc");
|
|
|
|
export const insert = async (userId: number, slug: string, title: string): Promise<Article> => {
|
|
const data: Record<string, any> = {
|
|
users_id: userId,
|
|
slug,
|
|
title,
|
|
file: `pages/${slug}.md`,
|
|
deleted: false,
|
|
created_at: new Date()
|
|
};
|
|
|
|
return db("articles").insert(data)
|
|
.returning("id")
|
|
.then(([{ id: id }]: { id: number }[]) => ({
|
|
id,
|
|
...data
|
|
} as Article))
|
|
};
|