coba.ts

mail@pastecode.io avatar
unknown
typescript
a year ago
2.0 kB
4
Indexable
Never
import { ClientBase } from 'pg';
import { Request, Response } from 'lambda-api';
import { getAuth } from '../../../shared/libs/auth';
import { failure, success } from '../../../shared/libs/response';
import code from '../../../shared/libs/code';
import { validateParameterNumber } from '../../../shared/libs/validation';
import { getReligion } from '../../../shared/functions/general-service';

async function getStudent(
  db: ClientBase,
  tenantUuid: string,
  studentId: number
): Promise<any> {
  try {

    const queryResult = await db.query(`
      select student.student_id,
             student.student_name,
             student.religion_id
      from student
      where deleted_at is null
        and tenant_uuid = $1
        and student_id = $2
    `, [
      tenantUuid,
      studentId,
    ]);

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

    return queryResult.rows[0];

  } catch (e) {
    console.error('[ERROR-QUERY] - func: getStudent', e);
    throw Error(code.database_error);
  }
}

function validateParameters(req: Request) {
  const studentId = validateParameterNumber(req.params.student_id);

  if (
    !studentId
  ) {
    throw Error(code.input_invalid);
  }

  return {
    student_id: studentId,
  };
}

export default async function coba(req: Request, res: Response): Promise<any> {
  try {
    const auth = getAuth(req);
    const param = validateParameters(req);

    const student = await getStudent(req.namespace.db, auth.tenant_uuid, param.student_id);

    if (student) {
      const religion = await getReligion(req, student.religion_id);
      // console.log('religion', religion);
      student.religion_name = religion.religion_name;
    }


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