Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // This mirrors the SQL table (ID and timestamps generated automatically)
- interface Product {
- id: number;
- name: string;
- comment?: string;
- category: number;
- created_at: string;
- updated_at: string;
- }
- export async function selectAll(): Promise<Product[]> {
- const rows = await knex<Product>("products").select();
- return rows;
- }
- export async function selectByID(id: number): Promise<Product> {
- const rows = await knex<Product>("products").select().where("id", id);
- return rows[0];
- }
- export async function selectByName(
- name: string,
- strategy: string
- ): Promise<Product[]> {
- const query = knex<Product>("products").select();
- switch (strategy) {
- case "exact":
- query.where("name", name);
- break;
- case "contains":
- query.where("name", "like", `%${name}%`);
- break;
- default:
- query.where("name", "like", `${name}%`);
- }
- query.then((rows: Product[]) => rows);
- return query;
- }
- export async function insert(
- name: string,
- category: number,
- comment: string
- ): Promise<Product> {
- await knex<Product>("products").insert({
- name: name,
- category: category,
- comment: comment,
- });
- const newProduct = await selectByName(name, "exact");
- if (newProduct.length != 1) {
- throw new Error("Error when inserting new product");
- } else {
- return newProduct[0];
- }
- }
- export async function update(product: Product): Promise<Product> {
- await knex<Product>("products").where("id", product.id).update({
- name: product.name,
- category: product.category,
- comment: product.comment,
- updated_at: knex.fn.now(),
- });
- return await selectByID(product.id);
- }
- export async function remove(id: number): Promise<{ message: string }> {
- await knex<Product>("products").where("id", id).del();
- const message = ResponseMessages.DeleteOK.message;
- return { message };
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement