Hi Matt,
Actually, there are to files. One is called db.js, which follows:
import mongodb from 'mongodb'
import Grid from 'gridfs-stream'
import multer from 'multer'
import GridFsStorage from 'multer-gridfs-storage'
import path from 'path'
import crypto from 'crypto'
const MongoClient = mongodb.MongoClient
const url = process.env.MONGO_DB_URL
const mongodbOptions = {
useNewUrlParser: true,
useUnifiedTopology: true
}
const client = new MongoClient(url, mongodbOptions)
const fileHandler = (bucketName) => (req, file) => {
return new Promise((resolve, reject) => {
crypto.randomBytes(16, (err, buf) => {
if (err) {
return reject(err)
}
const filename = buf.toString('hex') + path.extname(file.originalname)
// The prop metadata.expires indicates an expiration date in ms for the case where the request fails for any reason.
// In this (failure) scenario, the expired files can be removed safely.
// It is the responsability of further request processors (controllers), to remove metadata.expires property
// from the files it has properly processed or to remove the file (or files), when applicable.
// An aditional cron job may be created in order to remove orfanned expired files.
const fileInfo = {
filename: filename,
bucketName,
metadata: {
originalName: file.originalname,
encoding: file.encoding,
mimetype: file.mimetype,
size: file.size,
expires: Date.now() + 1000 * 60 * 60
}
}
resolve(fileInfo)
})
})
}
const storage = (dbName, bucketName) => {
const storageUrl = `${url}/${dbName}`
console.log({ storageUrl })
return new GridFsStorage({
url: storageUrl,
file: fileHandler(bucketName)
})
}
// accepted options: { fileFilter, limits, preservePath }
const makeUpload = async (dbName, bucketName, options = {}) =>
multer({ storage: storage(dbName, bucketName), ...options })
const makeGridStream = async (dbName, bucketName) => {
if (!client.isConnected()) {
await client.connect()
}
const db = client.db(dbName)
const gfs = Grid(db, mongodb)
gfs.collection(bucketName)
return gfs
}
const makeBucket = async (dbName, options) => {
if (!client.isConnected()) {
await client.connect()
}
const db = client.db(dbName)
return new mongodb.GridFSBucket(db, options)
}
export { client, makeUpload, makeGridStream, makeBucket }
The second one is called authenticationDB.js:
import { client } from './db'
const dbName = process.env.AUTH_DB_NAME
const authenticationDb = async () => {
const dbClient = await client
if (!dbClient.isConnected()) {
await dbClient.connect()
}
const db = dbClient.db(dbName)
return db
}
export default authenticationDb
This is the actual code, which, despite de warning is working properly.
Thanks in advance!