plutoapi-v2/src/models/betterzon/categories/categories.service.ts

99 lines
2.0 KiB
TypeScript

import * as dotenv from 'dotenv';
import {Category} from './category.interface';
import {Categories} from './categories.interface';
import {BetterzonDB} from '../Betterzon.db';
dotenv.config();
/**
* Data Model Interfaces
*/
/**
* Service Methods
*/
/**
* Fetches and returns all known categories
*/
export const findAll = async (): Promise<Categories> => {
let conn = await BetterzonDB.getConnection();
let categRows = [];
try {
const rows = await conn.query('SELECT category_id, name FROM categories');
for (let row in rows) {
if (row !== 'meta') {
let categ: Category = {
category_id: 0,
name: ''
};
const sqlCateg = rows[row];
categ.category_id = sqlCateg.category_id;
categ.name = sqlCateg.name;
categRows.push(categ);
}
}
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
}
return categRows;
};
/**
* Fetches and returns the category with the specified id
* @param id The id of the category to fetch
*/
export const find = async (id: number): Promise<Category> => {
let conn = await BetterzonDB.getConnection();
let categ: any;
try {
const rows = await conn.query('SELECT category_id, name FROM categories WHERE category_id = ?', id);
for (let row in rows) {
if (row !== 'meta') {
categ = rows[row];
}
}
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
}
return categ;
};
/**
* Fetches and returns all categories that match the search term
* @param term the term to match
*/
export const findBySearchTerm = async (term: string): Promise<Categories> => {
let conn = await BetterzonDB.getConnection();
let categRows = [];
try {
term = '%' + term + '%';
const rows = await conn.query('SELECT category_id, name FROM categories WHERE name LIKE ?', term);
for (let row in rows) {
if (row !== 'meta') {
categRows.push(rows[row]);
}
}
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
}
return categRows;
};