tnc-ca-geo / animl-api

Backend for https://animl.camera
4 stars 0 forks source link

TypeScript: Models(Camera) #209

Closed alukach closed 1 week ago

alukach commented 2 weeks ago

What I'm changing

This PR converts the Camera model to TS.

How I did it

There's a pattern throughout these classes that I have been removing. In this pattern, there is an operation function that is run with retry, like so:

const operation = async (input) => {
  return await retry(async (bail, attempt) => {
    // ... do something
  }, { retries: 2 });
};

try {
  await operation(someInput);
  // ...
  return { isOk: true };
} catch (err) {
  if (err instanceof GraphQLError) throw err;
  throw new InternalServerError(err);
}

This makes it a bit more onerous to write types for, as we need to type the input for the operation function. A simpler pattern looks like the following, where we replace the operation call with the contents of the function:

try {
  await retry(async (bail, attempt) => {
    // ... do something
  }, { retries: 2 });
  // ...
  return { isOk: true };
} catch (err) {
  if (err instanceof GraphQLError) throw err;
  throw new InternalServerError(err);
}

Before

    const saveWirelessCamera = async (input) => {
      const { projectId, cameraId, make, model } = input;
      return await retry(async () => {
        const newCamera = new WirelessCamera({
          _id: cameraId,
          make,
          projRegistrations: [{ projectId, active: true }],
          ...(model && { model })
        });
        await newCamera.save();
        return newCamera;
      }, { retries: 2 });
    };

    try {
      // create Wireless Camera record
      const camera = await saveWirelessCamera({ ...input, projectId });

After

    try {
      // create Wireless Camera record
      const camera = await await retry(
        async () => {
          const newCamera = new WirelessCamera({
            _id: input.cameraId,
            make: input.make,
            projRegistrations: [{ projectId, active: true }],
            model: input.model,
          });
          await newCamera.save();
          return newCamera;
        },
        { retries: 2 },
      );

Part of #187