Advertisement
Guest User

TS-question 2021-05-18

a guest
May 18th, 2021
612
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // This mirrors the SQL table (ID and timestamps generated automatically)
  2. interface Product {
  3.   id: number;
  4.   name: string;
  5.   comment?: string;
  6.   category: number;
  7.   created_at: string;
  8.   updated_at: string;
  9. }
  10.  
  11. export async function selectAll(): Promise<Product[]> {
  12.   const rows = await knex<Product>("products").select();
  13.   return rows;
  14. }
  15.  
  16. export async function selectByID(id: number): Promise<Product> {
  17.   const rows = await knex<Product>("products").select().where("id", id);
  18.   return rows[0];
  19. }
  20.  
  21. export async function selectByName(
  22.   name: string,
  23.   strategy: string
  24. ): Promise<Product[]> {
  25.   const query = knex<Product>("products").select();
  26.  
  27.   switch (strategy) {
  28.     case "exact":
  29.       query.where("name", name);
  30.       break;
  31.     case "contains":
  32.       query.where("name", "like", `%${name}%`);
  33.       break;
  34.     default:
  35.       query.where("name", "like", `${name}%`);
  36.   }
  37.  
  38.   query.then((rows: Product[]) => rows);
  39.   return query;
  40. }
  41.  
  42. export async function insert(
  43.   name: string,
  44.   category: number,
  45.   comment: string
  46. ): Promise<Product> {
  47.   await knex<Product>("products").insert({
  48.     name: name,
  49.     category: category,
  50.     comment: comment,
  51.   });
  52.   const newProduct = await selectByName(name, "exact");
  53.   if (newProduct.length != 1) {
  54.     throw new Error("Error when inserting new product");
  55.   } else {
  56.     return newProduct[0];
  57.   }
  58. }
  59.  
  60. export async function update(product: Product): Promise<Product> {
  61.   await knex<Product>("products").where("id", product.id).update({
  62.     name: product.name,
  63.     category: product.category,
  64.     comment: product.comment,
  65.     updated_at: knex.fn.now(),
  66.   });
  67.   return await selectByID(product.id);
  68. }
  69.  
  70. export async function remove(id: number): Promise<{ message: string }> {
  71.   await knex<Product>("products").where("id", id).del();
  72.   const message = ResponseMessages.DeleteOK.message;
  73.   return { message };
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement