add script to add total size to all user accounts, add totalSize to user model, return totalSize from user api request

This commit is contained in:
Cassie Tarakajian 2019-08-08 17:34:49 -04:00
parent 5654ed1922
commit 36d20281db
6 changed files with 88 additions and 41 deletions

View file

@ -108,24 +108,26 @@ export function copyObjectInS3(req, res) {
}); });
} }
export function listObjectsInS3ForUser(req, res) { export function listObjectsInS3ForUser(userId) {
const { username } = req.user; let assets = [];
findUserByUsername(username, (user) => { return new Promise((resolve) => {
const userId = user.id;
const params = { const params = {
s3Params: { s3Params: {
Bucket: `${process.env.S3_BUCKET}`, Bucket: `${process.env.S3_BUCKET}`,
Prefix: `${userId}/` Prefix: `${userId}/`
} }
}; };
let assets = [];
client.listObjects(params) client.listObjects(params)
.on('data', (data) => { .on('data', (data) => {
assets = assets.concat(data.Contents.map(object => ({ key: object.Key, size: object.Size }))); assets = assets.concat(data.Contents.map(object => ({ key: object.Key, size: object.Size })));
}) })
.on('end', () => { .on('end', () => {
resolve();
});
}).then(() => {
return getProjectsForUserId(userId);
}).then((projects) => {
const projectAssets = []; const projectAssets = [];
getProjectsForUserId(userId).then((projects) => {
let totalSize = 0; let totalSize = 0;
assets.forEach((asset) => { assets.forEach((asset) => {
const name = asset.key.split('/').pop(); const name = asset.key.split('/').pop();
@ -154,8 +156,19 @@ export function listObjectsInS3ForUser(req, res) {
}); });
projectAssets.push(foundAsset); projectAssets.push(foundAsset);
}); });
res.json({ assets: projectAssets, totalSize }); return Promise.resolve({ assets: projectAssets, totalSize});
}).catch((err) => {
console.log('got an error');
console.log(err);
}); });
}
export function listObjectsInS3ForUserRequestHandler(req, res) {
const { username } = req.user;
findUserByUsername(username, (user) => {
const userId = user.id;
listObjectsInS3ForUser(userId).then((objects) => {
res.json(objects);
}); });
}); });
} }

View file

@ -17,7 +17,8 @@ export function userResponse(user) {
preferences: user.preferences, preferences: user.preferences,
apiKeys: user.apiKeys, apiKeys: user.apiKeys,
verified: user.verified, verified: user.verified,
id: user._id id: user._id,
totalSize: req.user.totalSize
}; };
} }

View file

@ -0,0 +1,28 @@
import mongoose from 'mongoose';
import User from '../models/user';
import { listObjectsInS3ForUser } from '../controllers/aws.controller';
// Connect to MongoDB
mongoose.Promise = global.Promise;
mongoose.connect(process.env.MONGO_URL, { useMongoClient: true });
mongoose.connection.on('error', () => {
console.error('MongoDB Connection Error. Please make sure that MongoDB is running.');
process.exit(1);
});
User.find({}, {}, { timeout: true }).cursor().eachAsync((user) => {
console.log(user.id);
if (user.totalSize !== undefined) {
console.log('Already updated size for user: ' + user.username);
return Promise.resolve();
}
return listObjectsInS3ForUser(user.id).then((objects) => {
return User.findByIdAndUpdate(user.id, { $set: { totalSize: objects.totalSize } });
}).then(() => {
console.log('Updated new total size for user: ' + user.username);
});
}).then(() => {
console.log('Done iterating over every user');
process.exit(0);
});

View file

@ -1,3 +1,7 @@
require('@babel/register'); require('@babel/register');
require('@babel/polyfill'); require('@babel/polyfill');
require('./truncate'); const path = require('path');
require('dotenv').config({ path: path.resolve('.env') });
require('./populateTotalSize');
// require('./moveBucket');
// require('./truncate');

View file

@ -66,7 +66,8 @@ const userSchema = new Schema({
soundOutput: { type: Boolean, default: false }, soundOutput: { type: Boolean, default: false },
theme: { type: String, default: 'light' }, theme: { type: String, default: 'light' },
autorefresh: { type: Boolean, default: false } autorefresh: { type: Boolean, default: false }
} },
totalSize: { type: Number, default: 0 }
}, { timestamps: true, usePushEach: true }); }, { timestamps: true, usePushEach: true });
/** /**

View file

@ -7,6 +7,6 @@ const router = new Router();
router.post('/S3/sign', isAuthenticated, AWSController.signS3); router.post('/S3/sign', isAuthenticated, AWSController.signS3);
router.post('/S3/copy', isAuthenticated, AWSController.copyObjectInS3); router.post('/S3/copy', isAuthenticated, AWSController.copyObjectInS3);
router.delete('/S3/:object_key', isAuthenticated, AWSController.deleteObjectFromS3); router.delete('/S3/:object_key', isAuthenticated, AWSController.deleteObjectFromS3);
router.get('/S3/objects', AWSController.listObjectsInS3ForUser); router.get('/S3/objects', AWSController.listObjectsInS3ForUserRequestHandler);
export default router; export default router;