@riturajgc/upload-manager-service
Version:
Upload manager service for bitnudge
181 lines (169 loc) • 5.57 kB
JavaScript
const errorObject = require('../utils/errorObject');
const fs = require('fs');
const { promisify } = require('util');
const sizeOf = promisify(require('image-size'));
const utils = require('../../functions/utils');
class Storage{
constructor({ model }){
this.model = model;
}
async statusChange({ fileId, status }){
try{
if(!fileId || status == undefined){
return {status: false, message: `Please provide all the fields - ${!fileId?'fieldId, ':''} ${!status?'status':''} missing`}
}
await this.model.updateOne({
_id:fileId
},{
$set:{
isActive:status
},
$push:{
history:{
isActive:status,
changedAt:new Date()
}
}
});
return {status:true};
}catch(err){
console.error("Error in saveDocument",err);
return errorObject({message:"There is some problem, please try after some time"});
}
}
}
class StoreInDB extends Storage{
constructor({ model }){
super({ model });
this.model = model;
}
async fetch({ query, projection, skip, limit }){
try{
if(!query || !projection){
return {status:false, message: `Please provide all the fields - ${!query?'query, ':''} ${!projection?'projection':''} missing`}
}
if( typeof query !== "object" || typeof projection !== "object"){
return {status:false, message: `Please provide all the valid fields - ${typeof query !== "object"?'query, ':''} ${typeof projection !== "object"?'projection':''} should be type of object`}
}
const skipObj = skip ? skip : 0;
const limitObj = limit ? limit : 10;
let queryObj = {};
if(query.userId){
queryObj["source.userId"] = query.userId;
}
if(query.fileId){
queryObj["_id"] = query.fileId
}
if(query.hash){
queryObj["hash"] = query.hash
}
const result = await this.model.find(queryObj,projection).skip(skipObj).limit(limitObj).sort({createdAt:-1});
return {status:true,data:result};
}catch(err){
console.error("Error in fetchDocument",err);
return errorObject({message:"There is some problem, Please try after some time"});
}
}
async save({ userId, filePath, fileName, device, isThumbnailRequired ,thumbnailSize, creationFrom, thresholds}){
try{
console.log('start 1')
if(!userId || !filePath || !fileName || !device || isThumbnailRequired === undefined || isThumbnailRequired === null || !thumbnailSize || !creationFrom){
return errorObject({message:`Please provide all the valid fields -
${!userId?'userId, ':''}
${!filePath?'filePath, ':''}
${!fileName?'fileName, ':''}
${isThumbnailRequired === undefined || isThumbnailRequired === null?'thumbnail boolean, ':''}
${!thumbnailSize?'thumbnailSize, ':''}
${!creationFrom?'creationFrom':''} missing`})
}
console.log('start 2')
const imageTypes = ['png','jpeg','jpg']
const fileBuffer = await fs.readFileAsync(filePath);
const stats = await fs.statAsync(filePath);
let dimensions;
let hash;
let isValid;
const fileType = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase()
// const isImage = imageTypes.includes(fileType);
const isImage = false;
const hashObj = await utils.createHash(filePath);
if(hashObj.status){
hash = hashObj.data;
}
console.log('start 3')
if(isImage){
dimensions = await sizeOf(filePath);
// isValid = utils.isValidImage({size:Number(stats.size),height:dimensions.height,width:dimensions.width,type:dimensions.type}, thresholds);
}
// else{
// isValid = utils.isValidFileSize({size:Number(stats.size),fileType,thresholds});
// }
// if(!isValid.status){
// return errorObject({message:isValid.message});
// }
let document = {
source:{
device,
userId,
creationFrom,
},
file:{
name:fileName,
fileType,
content:fileBuffer,
height: isImage && dimensions ? dimensions.height : 1000,
width: isImage && dimensions ? dimensions.width : 1000,
size:stats.size
},
history:{
changedAt:new Date(),
isActive:true,
actionBy: {
device,
userId,
}
},
hash:hash
};
console.log('start 4 ')
const result = await this.model.create(document);
console.log('start 5 ')
if(isThumbnailRequired && isImage){
utils.createThumbnail(this.model,result,fileName,filePath,thumbnailSize);
}
return {status:true,data:result};
}catch(err){
console.error("Error in saveDocument",err);
return errorObject({message:"There is some problem, please try after some time"});
}
}
}
class StoreInFS extends Storage{
constructor({ model }){
super({ model });
this.model = model;
}
async fetch(){
//TODO: Define fetch method for FS Storage type
}
async save(){
//TODO: Define save method for FS Storage type
}
}
class StoreInS3 extends Storage{
constructor({ model }){
super({ model });
this.model = model;
}
async fetch(){
//TODO: Define fetch method for S3 Storage type
}
async save(){
//TODO: Define save method for S3 Storage type
}
}
module.exports = {
DB: StoreInDB,
FS: StoreInFS,
S3: StoreInS3,
};