import { Document, FilterQuery, Model, Schema, model, models } from "mongoose"; import { ARCA_WSAA_ENVIRONMENT, ARCA_WSAA_SERVICE, ArcaWsaaTokenLookupParams, CreateArcaWsaaTokenParams, IArcaWsaaToken, IArcaWsaaTokensAdapter, UpdateArcaWsaaTokenParams, } from "./ArcaWsaaTokens.Interface"; export interface IArcaWsaaTokenDocument extends Omit, Document {} export class ArcaWsaaTokensAdapterMongoose implements IArcaWsaaTokensAdapter { schema: Schema; arcaWsaaTokenList: Model; constructor() { this.schema = new Schema({ companyId: { type: Schema.Types.ObjectId, required: true, ref: "Company", index: true, }, service: { type: String, required: true, enum: Object.values(ARCA_WSAA_SERVICE), index: true, }, environment: { type: String, required: true, enum: Object.values(ARCA_WSAA_ENVIRONMENT), index: true, }, token: { type: String, required: true }, sign: { type: String, required: true }, generationTime: { type: Date, required: false }, expirationTime: { type: Date, required: true, index: true }, createdAt: { type: Date, required: true, default: Date.now }, updatedAt: { type: Date, required: true, default: Date.now }, }); this.schema.index({ companyId: 1, service: 1, environment: 1 }, { unique: true }); this.arcaWsaaTokenList = models.ArcaWsaaToken || model("ArcaWsaaToken", this.schema); } public async create(data: CreateArcaWsaaTokenParams): Promise { return await this.arcaWsaaTokenList.create(data); } private buildSearchCriteria( filters: Partial ): FilterQuery { const searchCriteria: FilterQuery = {}; if (filters.companyId) searchCriteria.companyId = filters.companyId; if (filters.service) searchCriteria.service = filters.service; if (filters.environment) searchCriteria.environment = filters.environment; return searchCriteria; } public async find(filters: Partial): Promise { return this.arcaWsaaTokenList.find(this.buildSearchCriteria(filters)).sort({ createdAt: -1 }).exec(); } public async findOne( filters: Partial ): Promise { return this.arcaWsaaTokenList.findOne(this.buildSearchCriteria(filters)).exec(); } public async update(data: UpdateArcaWsaaTokenParams): Promise { const { companyId, service, environment, ...updateData } = data; return this.arcaWsaaTokenList .findOneAndUpdate(this.buildSearchCriteria({ companyId, service, environment }), updateData, { new: true, }) .exec(); } public async upsert(data: CreateArcaWsaaTokenParams): Promise { const { companyId, service, environment, createdAt, ...updateData } = data; return this.arcaWsaaTokenList .findOneAndUpdate( this.buildSearchCriteria({ companyId, service, environment }), { $set: updateData, $setOnInsert: { companyId, service, environment, createdAt } }, { new: true, upsert: true } ) .exec(); } }