Refactor FilesAdapter to ES6 style.

This commit is contained in:
Nikita Lutsenko
2016-02-08 22:51:58 -08:00
parent 244febf4a9
commit 53fdc9bdeb
4 changed files with 57 additions and 57 deletions

View File

@@ -3,46 +3,41 @@
// Stores files in Mongo using GridStore
// Requires the database adapter to be based on mongoclient
var GridStore = require('mongodb').GridStore;
var path = require('path');
import { GridStore } from 'mongodb';
// For a given config object, filename, and data, store a file
// Returns a promise
function create(config, filename, data) {
return config.database.connect().then(() => {
var gridStore = new GridStore(config.database.db, filename, 'w');
return gridStore.open();
}).then((gridStore) => {
return gridStore.write(data);
}).then((gridStore) => {
return gridStore.close();
});
}
import * as Path from 'path';
import { FilesAdapter } from './FilesAdapter';
// Search for and return a file if found by filename
// Resolves a promise that succeeds with the buffer result
// from GridStore
function get(config, filename) {
return config.database.connect().then(() => {
return GridStore.exist(config.database.db, filename);
}).then(() => {
var gridStore = new GridStore(config.database.db, filename, 'r');
return gridStore.open();
}).then((gridStore) => {
return gridStore.read();
});
}
class GridStoreAdapter extends FilesAdapter {
// For a given config object, filename, and data, store a file
// Returns a promise
createFileAsync(config, filename, data) {
return config.database.connect().then(() => {
let gridStore = new GridStore(config.database.db, filename, 'w');
return gridStore.open();
}).then((gridStore) => {
return gridStore.write(data);
}).then((gridStore) => {
return gridStore.close();
});
}
// Generates and returns the location of a file stored in GridStore for the
// given request and filename
function location(config, req, filename) {
return (req.protocol + '://' + req.get('host') +
path.dirname(req.originalUrl) + '/' + req.config.applicationId +
getFileDataAsync(config, filename) {
return config.database.connect().then(() => {
return GridStore.exist(config.database.db, filename);
}).then(() => {
let gridStore = new GridStore(config.database.db, filename, 'r');
return gridStore.open();
}).then((gridStore) => {
return gridStore.read();
});
}
getFileLocation(config, request, filename) {
return (request.protocol + '://' + request.get('host') +
Path.dirname(request.originalUrl) + '/' + config.applicationId +
'/' + encodeURIComponent(filename));
}
}
module.exports = {
create: create,
get: get,
location: location
};
export default GridStoreAdapter;