@everytravel/shared
Version:
A comprehensive shared package for Everytravel containing Mongoose models and CRUD operations for hotel booking, user management, and transaction handling. Updated with improved model syntax and enhanced error handling.
38 lines (36 loc) • 1.82 kB
JavaScript
import mongoose from "mongoose";
const { Schema } = mongoose;
import { isCurrencyCode } from '../validation/index.js';
/**
* Transaction model for tracking user transactions.
*
* @typedef {Object} Transaction
* @property {ObjectId} user - Reference to the User who made the transaction.
* @property {Number} amount - Transaction amount.
* @property {String} currency - Currency code (e.g., USD).
* @property {String} status - Transaction status (e.g., "pending", "completed", "failed").
* @property {String} type - Transaction type (e.g., "booking", "ride", "refund", etc.).
* @property {Object} relatedEntity - Reference to the related entity (e.g., Booking, Ride, Suite).
* @property {ObjectId} relatedEntity.id - ID of the related entity.
* @property {String} relatedEntity.model - Model name of the related entity (e.g., "Booking", "Ride", "Suite").
* @property {Date} timestamp - Transaction timestamp.
*/
const TransactionSchema = new Schema({
user: { type: Schema.Types.ObjectId, ref: 'User' },
amount: { type: Number, min: 0 },
currency: { type: String, validate: { validator: (v) => !v || isCurrencyCode(v), message: 'currency must be a 3-letter code' } },
status: { type: String },
type: String, // e.g., "booking", "ride", "refund", etc.
relatedEntity: {
id: Schema.Types.ObjectId,
model: String, // "Booking", "Ride", "Suite", etc.
},
timestamp: Date,
});
// Indexes to optimize lookups and reporting
TransactionSchema.index({ user: 1, timestamp: -1 });
TransactionSchema.index({ status: 1 });
TransactionSchema.index({ type: 1 });
TransactionSchema.index({ 'relatedEntity.model': 1, 'relatedEntity.id': 1 });
const Transaction = mongoose.model('Transaction', TransactionSchema);
export default Transaction;