School Level Search

 avatar
unknown
typescript
3 years ago
2.4 kB
4
Indexable
import { ClientBase } from 'pg';
import { Request, Response } from 'lambda-api';
import { failure, success } from '../../../shared/libs/response';
import { SchoolLevelModel } from '../../../shared/models/school-level.model';
import { getAuth } from '../../../shared/libs/auth';
import code from '../../../shared/libs/code';

async function querySearchSchoolLevel(
  db: ClientBase,
  tenantUuid: string,
  params: any
): Promise<SchoolLevelModel> {
  try {
    let filterQueryIndex = 1;

    const filteredColumn = {
      school_level_id: 'school_level.school_level_id',
      school_level_name: 'school_level.school_level_name',
    };

    const queryStrings = [];
    const queryValues = [];

    for (const key in filteredColumn) {
      if (Object.prototype.hasOwnProperty.call(filteredColumn, key)) {
        const value = filteredColumn[key];

        if (!params[key] || params[key] === 'null' || params[key] === 'undefined') {
          continue;
        }

        queryStrings.push(`AND ${value} = $${++filterQueryIndex}`);

        queryValues.push(params[key] || null);
      }
    }

    const queryResult = await db.query(
      `
            SELECT school_level.school_level_id,
                   school_level.school_level_name,
                   school_level.school_level_description,
                   school_level.school_level_uuid
            FROM school_level
            WHERE school_level.tenant_uuid = $1
                AND school_level.deleted_at IS NULL
                ${queryStrings.join(' ')}
            ORDER BY school_level.school_level_id`,
      [tenantUuid, ...queryValues]
    );

    if (queryResult.rows.length === 0) {
      return null;
    }

    return queryResult.rows[0];
  } catch (e) {
    console.error('[ERROR-QUERY] - func: querySearchSchoolLevel', e);
    throw Error(code.database_error);
  }
}

export default async function schoolLevelSearch(req: Request, res: Response): Promise<any> {
  try {
    const auth = getAuth(req);
    const param = req.body;
    const schoolLevel = await querySearchSchoolLevel(req.namespace.db, auth.tenant_uuid, param);

    success(res, {
      status: true,
      version: req.version,
      message: 'success',
      data: schoolLevel,
      meta: null,
    });
  } catch (e) {
    failure(res, e);
  }
}
Editor is loading...