import _ from "lodash"; import db from "../init/db"; import { Filter, ObjectId, MatchKeysAndValues } from "mongodb"; import MonkeyError from "../utils/error"; const COLLECTION_NAME = "ape-keys"; function getApeKeyFilter( uid: string, keyId: string ): Filter { return { _id: new ObjectId(keyId), uid, }; } class ApeKeysDAO { static async getApeKeys(uid: string): Promise { return await db .collection(COLLECTION_NAME) .find({ uid }) .toArray(); } static async getApeKey(keyId: string): Promise { return await db .collection(COLLECTION_NAME) .findOne({ _id: new ObjectId(keyId) }); } static async countApeKeysForUser(uid: string): Promise { const apeKeys = await this.getApeKeys(uid); return _.size(apeKeys); } static async addApeKey(apeKey: MonkeyTypes.ApeKey): Promise { const insertionResult = await db .collection(COLLECTION_NAME) .insertOne(apeKey); return insertionResult.insertedId.toHexString(); } private static async updateApeKey( uid: string, keyId: string, updates: MatchKeysAndValues ): Promise { const updateResult = await db .collection(COLLECTION_NAME) .updateOne(getApeKeyFilter(uid, keyId), { $inc: { useCount: _.has(updates, "lastUsedOn") ? 1 : 0 }, $set: _.pickBy(updates, (value) => !_.isNil(value)), }); if (updateResult.modifiedCount === 0) { throw new MonkeyError(404, "ApeKey not found"); } } static async editApeKey( uid: string, keyId: string, name: string, enabled: boolean ): Promise { const apeKeyUpdates = { name, enabled, modifiedOn: Date.now(), }; await this.updateApeKey(uid, keyId, apeKeyUpdates); } static async updateLastUsedOn(uid: string, keyId: string): Promise { const apeKeyUpdates = { lastUsedOn: Date.now(), }; await this.updateApeKey(uid, keyId, apeKeyUpdates); } static async deleteApeKey(uid: string, keyId: string): Promise { const deletionResult = await db .collection(COLLECTION_NAME) .deleteOne(getApeKeyFilter(uid, keyId)); if (deletionResult.deletedCount === 0) { throw new MonkeyError(404, "ApeKey not found"); } } } export default ApeKeysDAO;