createContract.ts 1.19 KB
import * as R from "ramda";
import { Context } from "../";
import Contract from "entity/Contract";
import Drone from "entity/Drone";
import User from "entity/User";
import Org from "entity/Org";

export default async (
  root: {},
  { input: { reason, date, droneId, area, address } },
  context: Context
) => {
  const { connection } = context;
  const contractRepo = connection.getRepository(Contract);
  const droneRepo = connection.getRepository(Drone);
  const userRepo = connection.getRepository(User);
  const orgRepo = connection.getRepository(Org);

  const userId = context.session.id;
  const user = await userRepo.findOneById(userId);

  if (R.isNil(user)) throw new Error("Session Error");

  const drone = await droneRepo.findOneById(droneId);

  if (R.isNil(drone)) throw new Error("Invalid Drone ID");

  const org = await orgRepo.findOne({ where: { name: area } });

  let contract = new Contract();

  contract.reason = reason;
  contract.date = date;
  contract.area = area;
  contract.address = address;
  contract.drone = drone;
  contract.status = "wait";
  contract.review = "심사중";
  contract.writer = user!;
  contract.org = org!;

  await contractRepo.save(contract);
  return contract;
};