Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BeforeRequest and AfterCommit Event #50

Closed
wants to merge 4 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 55 additions & 23 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ var fs = require('fs'),

function Fileupload(name, options) {
Collection.apply(this, arguments);

// check to see if config has everything we need...
if (!this.config.properties || !this.config.directory || !this.config.fullDirectory) {
var dir = "_" + name;
Expand Down Expand Up @@ -71,16 +71,16 @@ function Fileupload(name, options) {
}
};
this.properties = this.config.properties;

this.config.directory = dir;
this.config.fullDirectory = path.join(__dirname, publicDir, dir);

// write the config file since it was apparently incomplete before
fs.writeFile(path.join(options.configPath, 'config.json'), JSON.stringify(this.config), function(err) {
if (err) throw err;
});
}

// If the directory doesn't exist, we'll create it
try {
fs.statSync(this.config.fullDirectory).isDirectory();
Expand All @@ -91,20 +91,29 @@ function Fileupload(name, options) {

util.inherits(Fileupload, Collection);

Fileupload.events = ["Get", "Post", "Delete"];
Fileupload.events = ["Get", "Post", "Delete", "beforeRequest", "afterCommit"];
Fileupload.dashboard = Collection.dashboard;

/**
* Module methods
*/
Fileupload.prototype.handle = function (ctx, next) {

if (this.events.beforeRequest) {
this.events.beforeRequest.run(ctx, {
url: ctx.url,
filename: ctx.url
}, function (err) {
if (err) return ctx.done(err);
});
}
ctx.query.id = ctx.query.id || this.parseId(ctx) || (ctx.body && ctx.body.id);
var req = ctx.req,
self = this;

if (req.method === "POST") { // not clear what to do with PUTs yet...
ctx.body = {};

var form = new formidable.IncomingForm(),
uploadDir = this.config.fullDirectory,
resultFiles = [],
Expand All @@ -114,11 +123,21 @@ Fileupload.prototype.handle = function (ctx, next) {
var processDone = function(err, fileInfo) {
if (err) return ctx.done(err);
resultFiles.push(fileInfo);

remainingFile--;
if (remainingFile === 0) {
debug("Response sent: ", resultFiles);
return ctx.done(null, resultFiles); // TODO not clear what to do here yet
if (self.events.afterCommit) {
self.events.afterCommit.run(ctx, {
url: ctx.url,
result: resultFiles,
}, function (err) {
if (err) return ctx.done(err);
return ctx.done(null, resultFiles); // TODO not clear what to do here yet
});
} else {
return ctx.done(null, resultFiles); // TODO not clear what to do here yet
}
}
};

Expand All @@ -137,7 +156,7 @@ Fileupload.prototype.handle = function (ctx, next) {
fs.mkdir(uploadDir);
}
}

ctx.body[propertyName] = req.query[propertyName];
}
}
Expand All @@ -148,17 +167,30 @@ Fileupload.prototype.handle = function (ctx, next) {
fs.rename(file.path, path.join(uploadDir, file.name), function(err) {
if (err) return processDone(err);
debug("File renamed after event.upload.run: %j", err || path.join(uploadDir, file.name));

ctx.body.filename = file.name;
ctx.body.originalFilename = file.originalFilename;

ctx.body.filesize = file.size;
ctx.body.creationDate = new Date().getTime();

// Store MIME type in object
ctx.body.type = mime.lookup(file.name);

self.save(ctx, processDone);

if (self.events.afterCommit) {
self.events.afterCommit.run(ctx, {
url: ctx.url,
result: resultFiles,
}, function (err) {
if (err) return ctx.done(err);
return ctx.done(null, resultFiles);
});

self.save(ctx, processDone);
} else {
self.save(ctx, processDone);
return ctx.done(null, resultFiles);
}
});
};

Expand All @@ -167,7 +199,7 @@ Fileupload.prototype.handle = function (ctx, next) {
debug("File %j received", file.name);
file.originalFilename = file.name;
file.name = md5(Date.now()) + '.' + file.name.split('.').pop();

renameAndStore(file);
}).on('fileBegin', function(name, file) {
remainingFile++;
Expand All @@ -176,7 +208,7 @@ Fileupload.prototype.handle = function (ctx, next) {
debug("Error: %j", err);
return processDone(err);
});

return req.resume();
} else if (req.method === "DELETE") {
this.del(ctx, ctx.done);
Expand All @@ -191,40 +223,40 @@ Fileupload.prototype.handle = function (ctx, next) {
Fileupload.prototype.del = function(ctx, next) {
var self = this;
var uploadDir = this.config.fullDirectory;

this.find(ctx, function(err, result) {
if (err) return ctx.done(err);

// let the collection handle the store... we just care about the files themselves
self.remove(ctx, function(err) {
if (err) return ctx.done(err);

if (typeof result == 'undefined')
result = [];
else if (!Array.isArray(result))
result = [result];

var filesRemaining = result.length;

var finishedFcn = function(err) {
if (err) return ctx.done(err);
filesRemaining--;

if (filesRemaining === 0) {
var filenames = result.map(function(r) {
return r.originalFilename;
});
next({statusCode: 200, message: "File " + filenames + " successfuly deleted"});
}
};

result.forEach(function(toDelete) {
var filepath;
if (toDelete.subdir)
filepath = path.join(uploadDir, toDelete.subdir, toDelete.filename);
else
filepath = path.join(uploadDir, toDelete.filename);

// actually delete the file, let the Collection methods handle events and whatever else
debug('deleting file',filepath);
fs.unlink(filepath, finishedFcn);
Expand Down