Created
May 20, 2016 13:15
-
-
Save azatoth/22f192e5ea403e3701492d993512e715 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var path = require('path'); | |
var Q = require('q'); | |
Q.longStackSupport = true; | |
module.exports = function (Content) { | |
Content.observe('before save', (ctx, next) => { | |
function getOldContent(name, pathId, counter, cb) { | |
var parsed = path.parse(name); | |
var filename = counter === 1 ? name : `${parsed.name} (${counter})${parsed.ext}`; | |
Content.findOne({ | |
where: { | |
pathId: pathId, | |
name: filename | |
} | |
}, (err, record) => { | |
if (!record) { | |
cb(filename); | |
} else { | |
getOldContent(name, pathId, counter + 1, cb); | |
} | |
}); | |
} | |
if (ctx.instance && ctx.isNewInstance) { | |
getOldContent(ctx.instance.name, ctx.instance.pathId, 1, (name) => { | |
ctx.instance.name = name; | |
next(); | |
}); | |
} else { | |
next(); | |
} | |
}); | |
Content.beforeRemote('upload', function (ctx, modelInstance, next) { | |
ctx.req.connection.setTimeout(8.64e+7); // 24h | |
next(); | |
}); | |
Content.upload = function (req, res, contentId, cb) { | |
var StorageContainer = Content.app.models.StorageContainer; | |
Q.nfcall(StorageContainer.getContainer, contentId) | |
.fail((err) => { | |
if (err.code === 'ENOENT') { | |
return Q.nfcall(StorageContainer.createContainer, { | |
name: contentId | |
}); | |
} | |
}) | |
.then((container) => { | |
Content.findById(contentId) | |
.then((content) => { | |
if (!content) { | |
return; | |
} | |
StorageContainer.upload(req, res, { | |
container: contentId, | |
getFilename: (fileInfo, req, res) => { | |
return content.name; | |
} | |
}, (err) => { | |
if (err) { | |
Content.destroyById(contentId); | |
return; | |
} | |
cb(err); | |
}); | |
}); | |
}) | |
.fail((err) => { | |
console.error(err); | |
}); | |
}; | |
Content.remoteMethod( | |
'upload', { | |
http: { | |
path: '/:id/upload', | |
verb: 'post' | |
}, | |
accepts: [{ | |
arg: 'req', | |
type: 'object', | |
'http': { | |
source: 'req' | |
} | |
}, { | |
arg: 'res', | |
type: 'object', | |
'http': { | |
source: 'res' | |
} | |
}, { | |
arg: 'id', | |
type: 'string' | |
}], | |
returns: { | |
arg: 'status', | |
type: 'string' | |
} | |
} | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment