Files
mbmanager-api/components/file/fileModel.js
T
2026-08-19 04:49:40 +03:30

44 lines
1.3 KiB
JavaScript

const mongoose = require('mongoose')
const ObjectID = mongoose.Schema.Types.ObjectId
const fileSchema = new mongoose.Schema(
{
fileName: {
type: String,
required: true,
},
owner: {
type: ObjectID,
ref: 'User',
},
fileEndpoint: String,
bucketName: {
type: String,
required: true,
},
},
{
toJSON: { virtuals: true },
toObject: { virtuals: true },
},
{ timestamps: true }
)
fileSchema.virtual('publicUrl').get(function () {
const protocol = process.env.AWS_USE_SSL === 'true' ? 'https://' : 'http://'
let endpoint = this.fileEndpoint || process.env.AWS_ENDPOINT || 'localhost'
if (!endpoint.startsWith('http://') && !endpoint.startsWith('https://')) {
const hostPort = process.env.AWS_PORT ? `${endpoint}:${process.env.AWS_PORT}` : endpoint
endpoint = `${protocol}${hostPort}`
}
return `${endpoint.replace(/\/$/, '')}/${this.bucketName}/${this.fileName}`
})
fileSchema.virtual('privateUrl').get(function () {
const apiUrl = (process.env.API_URL || '').replace(/\/$/, '')
return `${apiUrl}/api/files/get-image/${this.bucketName}/${this.fileName}`
})
const File = mongoose.model('file', fileSchema)
module.exports = File