50 lines
1.8 KiB
TypeScript
50 lines
1.8 KiB
TypeScript
import { Document, Model, Schema, model } from "mongoose";
|
|
import {
|
|
CreatePlanPaymentParams,
|
|
FindPlanPaymentsParams,
|
|
IPlanPayment,
|
|
IPlanPaymentsAdapter,
|
|
} from "./PlanPayments.interface";
|
|
|
|
export interface IPlanPaymentDocument extends Omit<IPlanPayment, "id">, Document {}
|
|
|
|
export class PlanPaymentsAdapterMongoose implements IPlanPaymentsAdapter {
|
|
schema: Schema;
|
|
planPaymentList: Model<IPlanPaymentDocument>;
|
|
|
|
constructor() {
|
|
this.schema = new Schema({
|
|
userId: { type: Schema.Types.ObjectId, required: true, ref: "User" },
|
|
subscriptionId: { type: Schema.Types.ObjectId, required: true, ref: "PlanSuscription" },
|
|
amount: { type: Number, required: true, default: 0 },
|
|
paymentDate: { type: Date, required: true, default: Date.now },
|
|
paymentMethod: { type: String, required: false },
|
|
status: { type: String, required: true },
|
|
transactionId: { type: String, required: false },
|
|
});
|
|
this.schema.index({ transactionId: 1 }, { unique: true, sparse: true });
|
|
|
|
this.planPaymentList = model<IPlanPaymentDocument>("PlanPayment", this.schema);
|
|
}
|
|
|
|
public async find(filters: FindPlanPaymentsParams): Promise<IPlanPayment[]> {
|
|
return this.planPaymentList.find(filters).exec();
|
|
}
|
|
|
|
public async create(data: CreatePlanPaymentParams): Promise<IPlanPayment> {
|
|
return this.planPaymentList.create(data);
|
|
}
|
|
|
|
public async createIfMissingByTransactionId(data: CreatePlanPaymentParams): Promise<IPlanPayment> {
|
|
if (!data.transactionId) {
|
|
return this.create(data);
|
|
}
|
|
|
|
return this.planPaymentList.findOneAndUpdate(
|
|
{ transactionId: data.transactionId },
|
|
{ $setOnInsert: data },
|
|
{ new: true, upsert: true, setDefaultsOnInsert: true }
|
|
).exec();
|
|
}
|
|
}
|