typeorm#getMongoRepository TypeScript Examples

The following examples show how to use typeorm#getMongoRepository. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.ts    From IBM-HyperProtectMBaaS with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
/**
 * This deletes outcomes based on matching taskUUID and taskOccurrenceIndex.
 * This does not delete based on UUID as the UUID for an updated outcome will be different since its an un-versioned object
 * @param outcome
 */
export async function deleteExistingOutcomeForUpdate(outcome: OCKOutcome) {
  await getMongoRepository(OCKOutcome).deleteOne({
    taskUUID: outcome.taskUUID,
    taskOccurrenceIndex: outcome.taskOccurrenceIndex,
  });
}
Example #2
Source File: utils.ts    From IBM-HyperProtectMBaaS with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
/**
 * This will set/save the UUID for the backend across microservice re-starts. While it would be functionally OK to generate a UUID each time
 * the microservice starts, it would lead to vector clock pollution, wasted space (as clocks get stored with entities) and a lot of network traffic
 * since the backend sync logic wouldn't find the clock with newly generated UUID in the vec clocks coming in from the frontend for a new microservice instance
 */
export async function getLocalUUID(): Promise<string> {
  if (uuid) {
    // optimization to prevent DB look up each time
    return uuid;
  }

  let repo = getMongoRepository(UUID);
  let mongoUuid = await repo.find();
  assert(mongoUuid.length < 2, "Multiple UUIDs found for local db");
  if (!mongoUuid.length) {
    const new_uuid = uuid_lib.v4().toUpperCase();
    await repo.insertOne(new UUID(new_uuid));
    return new_uuid;
  }
  assert(isNotEmpty(mongoUuid[0].uuid));
  return mongoUuid[0].uuid;
}
Example #3
Source File: utils.ts    From IBM-HyperProtectMBaaS with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
/**
 *
 * @param increment
 */
export async function createOrIncrementClock(increment: boolean = true) {
  uuid = await getLocalUUID();
  console.log("UUID : " + uuid);
  let repo = getMongoRepository(Process);
  let clock = await repo.findOne({ id: uuid });
  assert(uuid);
  if (!clock) await repo.insertOne(new Process(uuid, 0));
  else {
    if (increment) {
      assert(uuid);
      await repo.updateOne({ id: uuid }, { $inc: { clock: 1 } }, { upsert: true });
    }
  }
}
Example #4
Source File: utils.ts    From IBM-HyperProtectMBaaS with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
/**
 * Adds new (unknown) clocks to local db. It will set local clock to the max of twc clocks
 *
 * @param processes clocks (typically from a knowledge vector )
 */
export async function mergeKnowledgeVectors(processes: Process[]) {
  let clockRepo = getMongoRepository(Process);

  for (const process of processes) {
    const processExists = await clockRepo.findOne({ id: process.id });
    if (isEmpty(processExists)) {
      assert(isNotEmpty(process.id));
      await clockRepo.save(process);
    } else {
      assert(process.id === processExists.id);
      const maxClock = Math.max(processExists.clock, process.clock);
      if (maxClock === process.clock) await clockRepo.updateOne({ id: process.id }, { $set: { clock: maxClock } });
    }
  }
}
Example #5
Source File: utils.ts    From IBM-HyperProtectMBaaS with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
/**
 * Gets local knowledge vector (i.e all clocks stored in MongoDB)
 */
export async function getLatestKnowledgeVector(): Promise<KnowledgeVector> {
  const clocks = await getMongoRepository(Process).find();
  //console.log(clocks);
  assert(clocks.length > 0, "At least one clock must always exist");
  let kv = new KnowledgeVector();

  // paranoid check to ensure quality of UUID data in db
  clocks.forEach((process) => assert(isNotEmpty(process.id)));

  // Removes _id field
  kv.processes = clocks.map(({ _id, ...item }) => item) as Process[];

  return kv;
}
Example #6
Source File: utils.ts    From IBM-HyperProtectMBaaS with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
/**
 * Checks if outcome exists in db
 * @param outcome
 */
export async function isOutcomeNew(outcome: OCKOutcome): Promise<boolean> {
  const outcomeExists = await getMongoRepository(OCKOutcome).findOne({
    taskUUID: outcome.taskUUID,
    taskOccurrenceIndex: outcome.taskOccurrenceIndex,
  });
  return isNotEmpty(outcomeExists);
}
Example #7
Source File: CarePlanController.ts    From IBM-HyperProtectMBaaS with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
// Delete all carePlans in the collection
  static deleteCarePlans = async (req: Request, res: Response) => {
    const carePlanRepository = getMongoRepository(OCKCarePlan);
    try {
      await carePlanRepository.deleteMany({});
    } catch (e) {
      res.status(409).send("Does not exist");
      return;
    }

    //If all ok, send 201 response
    res.status(201).send("CarePlans deleted");
  };
Example #8
Source File: ContactController.ts    From IBM-HyperProtectMBaaS with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
// Delete all contacts in the collection
  static deleteContacts = async (req: Request, res: Response) => {
    const contactRepository = getMongoRepository(OCKContact);
    try {
      await contactRepository.deleteMany({});
    } catch (e) {
      res.status(409).send("Does not exist");
      return;
    }

    //If all ok, send 201 response
    res.status(201).send("Contacts deleted");
  };
Example #9
Source File: OutcomeController.ts    From IBM-HyperProtectMBaaS with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
// Delete all outcomes in the collection
  static deleteOutcomes = async (req: Request, res: Response) => {
    const outcomeRepository = getMongoRepository(OCKOutcome);
    try {
      await outcomeRepository.deleteMany({});
    } catch (e) {
      res.status(409).send("Does not exist");
      return;
    }

    //If all ok, send 201 response
    res.status(201).send("Outcomes deleted");
  };
Example #10
Source File: PatientController.ts    From IBM-HyperProtectMBaaS with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
// Delete all patients in the collection
  static deletePatients = async (req: Request, res: Response) => {
    const patientRepository = getMongoRepository(OCKPatient);
    try {
      await patientRepository.deleteMany({});
    } catch (e) {
      res.status(409).send("Does not exist");
      return;
    }

    //If all ok, send 201 response
    res.status(201).send("Patients deleted");
  };
Example #11
Source File: RevisionRecordController.ts    From IBM-HyperProtectMBaaS with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
// Delete all revisionRecords in the collection
  static deleteRevisionRecords = async (req: Request, res: Response) => {
    try {
      await getMongoRepository(OCKRevisionRecord).deleteMany({});
      await getMongoRepository(OCKTask).deleteMany({});
      await getMongoRepository(OCKOutcome).deleteMany({});
    } catch (e) {
      res.status(201).send("Does not exist");
      return;
    }

    //If all ok, send 201 response
    res.status(201).send("RevisionRecords deleted");
  };
Example #12
Source File: TaskController.ts    From IBM-HyperProtectMBaaS with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
// Delete all tasks in the collection
  static deleteTasks = async (req: Request, res: Response) => {
    const taskRepository = getMongoRepository(OCKTask);
    try {
      await taskRepository.deleteMany({});
    } catch (e) {
      res.status(409).send("Does not exist");
      return;
    }

    //If all ok, send 201 response
    res.status(201).send("Tasks deleted");
  };
Example #13
Source File: NotificationsRepository.ts    From GoBarber with MIT License 5 votes vote down vote up
constructor() {
    this.ormRepository = getMongoRepository(Notification, 'mongodb');
  }
Example #14
Source File: NotificationsRepository.ts    From gobarber-api with MIT License 5 votes vote down vote up
constructor() {
    this.ormRepository = getMongoRepository(Notification, 'mongo');
  }
Example #15
Source File: NotificationsRepository.ts    From gobarber-project with MIT License 5 votes vote down vote up
constructor() {
    this.ormRepository = getMongoRepository(Notification, 'mongo');
  }
Example #16
Source File: RevisionRecordController.ts    From IBM-HyperProtectMBaaS with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
static newRevisionRecord = async (req: Request, res: Response) => {
    const revRecord = req.body as OCKRevisionRecord;
    const revisionRecordRepository = getRepository(OCKRevisionRecord);

    // console.log(util.inspect(revRecord, false, null, true /* enable colors */));
    try {
      const revisionRecord = revisionRecordRepository.create(revRecord);
      await revisionRecordRepository.save(revisionRecord);

      for (let entity of revRecord.entities) {
        switch (entity.type) {

          case "task": {
            const taskRepository = getMongoRepository(OCKTask);
            await processEntity(entity, taskRepository);
            break;
          }
          case "outcome": {
            const outcomeRepository = getMongoRepository(OCKOutcome);
            // if this is an update, delete old version
            if (!(await isOutcomeNew(entity.object))) {
              await deleteExistingOutcomeForUpdate(entity.object);
            }
            await processEntity(entity, outcomeRepository);
            break;
          }
          case "careplan": {
            const careplanRepository = getMongoRepository(OCKCarePlan);
            await processEntity(entity, careplanRepository);
            break;
          }
          case "contact": {
            const contactRepository = getMongoRepository(OCKContact);
            // if this is an update, delete old version
            if (!(await isOutcomeNew(entity.object))) {
              await deleteExistingOutcomeForUpdate(entity.object);
            }
            await processEntity(entity, contactRepository);
            break;
          }
          case "patient": {
            const patientRepository = getMongoRepository(OCKPatient);
            await processEntity(entity, patientRepository);
            break;
          }
          default: {
            res.status(400).send("Bad request");
            return;
          }
        }
      }
    } catch (e) {
      res.status(409).send("Error processing request");
      return;
    }

    await mergeKnowledgeVectors(revRecord.knowledgeVector.processes);
    await createOrIncrementClock(); // increment after merging a revision

    //If all ok, send 201 response
    res.status(201).send("RevisionRecord stored");
  };
Example #17
Source File: NotificationsRepository.ts    From hotseat-api with MIT License 5 votes vote down vote up
constructor() {
    this.ormRepository = getMongoRepository(Notification, 'mongo');
  }
Example #18
Source File: RevisionRecordController.ts    From IBM-HyperProtectMBaaS with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
static listAll = async (req: Request, res: Response) => {
    console.log(util.inspect(req.query.knowledgeVector, false, null, true /* enable colors */));

    if (isEmpty(req.query.knowledgeVector)) {
      res
        .status(400)
        .send(
          'Must send an array of knowledge vectors as query param. An empty knowledge vector would be { processes: [{ id : "validUUIDv4" , clock : 0 } ]}'
        );
      return;
    }

    // Thorough JSON validation using JSON Schema, TypedJSON and class-validator
    const ajv = new Ajv();
    const valid = ajv.validate(kvSchema, req.query.knowledgeVector);
    if (!valid) {
      console.log(ajv.errors);
      res.status(400).send(ajv.errors);
      return;
    }

    let incomingKV: KnowledgeVector;
    try {
      incomingKV = new TypedJSON(KnowledgeVector).parse(req.query.knowledgeVector);
    } catch (error) {
      res.status(400).send("JSON schema error");
      return;
    }

    console.log(util.inspect(incomingKV, false, null, true /* enable colors */));

    const errors = await validate(incomingKV);
    if (errors.length > 0) {
      res.status(400).send(errors);
      return;
    }

    //console.log(util.inspect(incomingKV, false, null, true /* enable colors */));

    let returnRevRecord = new OCKRevisionRecord();
    returnRevRecord.entities = [];

    // Case 1 : iOS device is syncing for the first time, it has no knowledge of the servers clock
    if (isEmpty(incomingKV.processes.find((process) => process.id === uuid))) {
      // store incoming clock locally
      let clockRepo = getMongoRepository(Process);

      for (const process of incomingKV.processes) {
        assert(isUUID(process.id));
        const processExists = await clockRepo.findOne({ id: process.id });
        if (isEmpty(processExists)) {
          assert(isNotEmpty(process.id));
          await clockRepo.save(process);
        }
      }

      // send all outcomes and tasks
      const taskRepository = getMongoRepository(OCKTask);
      const tasks = await taskRepository.find({});

      const outcomeRepository = getMongoRepository(OCKOutcome);
      const outcomes = await outcomeRepository.find({});

      tasks.map((entity) => {
        delete entity.kv;
        returnRevRecord.entities.push({ type: "task", object: entity });
      });
      outcomes.map((entity) => {
        delete entity.kv;
        returnRevRecord.entities.push({ type: "outcome", object: entity });
      });

      // set kv for revisionRecord
      returnRevRecord.knowledgeVector = await getLatestKnowledgeVector();

      //console.log(util.inspect(returnRevRecord, false, null, true /* enable colors */));
      res.status(201).send(returnRevRecord);
      return;
    }

    // Case 2 : It has synced before but its clock might be older than local, send entities newer than clock
    const clock = incomingKV.processes.find((process) => process.id === uuid).clock;
    assert(!isEmpty(clock), "clock cannot be undefined at this point");

    const taskRepository = getMongoRepository(OCKTask);
    const tasks = await taskRepository.find({
      $and: [{ "kv.processes.clock": { $gt: clock } }, { "kv.processes.id": { $eq: uuid } }],
    });

    const outcomeRepository = getMongoRepository(OCKOutcome);
    const outcomes = await outcomeRepository.find({
      $and: [{ "kv.processes.clock": { $gt: clock } }, { "kv.processes.id": { $eq: uuid } }],
    });

    tasks.map((entity) => {
      delete entity.kv;
      returnRevRecord.entities.push({ type: "task", object: entity });
    });
    outcomes.map((entity) => {
      delete entity.kv;
      returnRevRecord.entities.push({ type: "outcome", object: entity });
    });

    // set kv for revisionRecord
    returnRevRecord.knowledgeVector = await getLatestKnowledgeVector();

    //console.log(util.inspect(returnRevRecord, false, null, true /* enable colors */));
    res.status(201).send(returnRevRecord);
  };