Skip to content
This repository has been archived by the owner on Jun 7, 2022. It is now read-only.

Commit

Permalink
Merge 23ef599 into f3cc2ed
Browse files Browse the repository at this point in the history
  • Loading branch information
ChristopheBraud committed Feb 28, 2018
2 parents f3cc2ed + 23ef599 commit a273d66
Show file tree
Hide file tree
Showing 13 changed files with 512 additions and 504 deletions.
9 changes: 9 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
root = true

[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
30 changes: 15 additions & 15 deletions .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,20 @@
"plugins": [
"indexof"
],
"extends": "eslint:recommended", // Recommended rules
"extends": [
"eslint:recommended",
"standard"
],
"rules": {
"quotes": [2, "single"], // single quotes are better
"semi": [2, "always"],
"max-len": [2, 120],
"max-lines": [2, 400],
"max-statements": [2, 20],
"no-tabs": [2],
"linebreak-style": [2, "unix"],
"no-multiple-empty-lines": [2, {"max": 1, "maxEOF": 0, "maxBOF": 0}],
"eol-last": [2, "always"],
"no-unsafe-negation": [2],
"eqeqeq": [2, "smart"],
"strict": [2, "never"],
"indexof/no-indexof": [2]
// Exception
"semi": ["error", "always"],
// Format xtras
"max-len": ["error", 120],
"max-lines": ["error", 400],
"max-statements": ["error", 20],
"linebreak-style": ["error", "unix"],
// Other xtras
"strict": ["error", "never"],
"indexof/no-indexof": ["error"]
}
}
}
109 changes: 54 additions & 55 deletions lib/handlers.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,75 +6,74 @@ const serviceAsset = require('./services/asset');
const forIn = require('for-in');
const buildLink = require('campsi/lib/modules/buildLink');

module.exports.postAssets = function postAssets(req, res) {

//TODO create our own structure for files, be independent from multer
serviceAsset.createAsset(req.service, req.files, req.user, req.headers)
.then((data) => helpers.json(res, data))
.catch(() => helpers.error(res));
module.exports.postAssets = function postAssets (req, res) {
// TODO create our own structure for files, be independent from multer
serviceAsset.createAsset(req.service, req.files, req.user, req.headers)
.then((data) => helpers.json(res, data))
.catch(() => helpers.error(res));
};

module.exports.getAssets = function getAssets(req, res) {
let pagination = {};
pagination.perPage = req.query.perPage;
pagination.page = req.query.page;
module.exports.getAssets = function getAssets (req, res) {
let pagination = {};
pagination.perPage = req.query.perPage;
pagination.page = req.query.page;

serviceAsset.getAssets(req.service, pagination, req.query.sort)
.then((data) => {
let links = [];
forIn(data.nav, (page, rel) => {
if(page !== data.page) {
links.push('<{0}>; rel="{1}"'.format(buildLink(req, page, ['perPage', 'sort']), rel));
}
});
let headers = {
'X-Total-Count': data.count,
'X-Page': data.page,
'X-Per-Page': data.perPage,
'X-Last-Page': data.nav.last
};
if(links.length) {
headers.Link = links.join(', ');
}
helpers.json(res, data.assets, headers);
})
.catch(() => {
helpers.error(res);
});
serviceAsset.getAssets(req.service, pagination, req.query.sort)
.then((data) => {
let links = [];
forIn(data.nav, (page, rel) => {
if (page !== data.page) {
links.push('<{0}>; rel="{1}"'.format(buildLink(req, page, ['perPage', 'sort']), rel));
}
});
let headers = {
'X-Total-Count': data.count,
'X-Page': data.page,
'X-Per-Page': data.perPage,
'X-Last-Page': data.nav.last
};
if (links.length) {
headers.Link = links.join(', ');
}
helpers.json(res, data.assets, headers);
})
.catch(() => {
helpers.error(res);
});
};

module.exports.sendLocalFile = function sendLocalFile(req, res) {
res.sendFile(path.join(req.service.options.storages.local.dataPath, req.params[0]));
module.exports.sendLocalFile = function sendLocalFile (req, res) {
res.sendFile(path.join(req.service.options.storages.local.dataPath, req.params[0]));
};

module.exports.streamAsset = function streamAsset(req, res) {
const url = req.storage.getAssetURL(req.asset);
const newReq = http.request(url, function (newRes) {
let headers = newRes.headers;
headers['Content-Disposition'] = 'attachment; filename="{0}"'.format(req.asset.originalName);
headers['Content-Type'] = req.asset.clientReportedMimeType;
headers['Content-Length'] = req.asset.size;
res.writeHead(newRes.statusCode, headers);
newRes.pipe(res);
}).on('error', function (err) {
debug('Streaming error: %s', err);
res.statusCode = 500;
res.end();
});
module.exports.streamAsset = function streamAsset (req, res) {
const url = req.storage.getAssetURL(req.asset);
const newReq = http.request(url, function (newRes) {
let headers = newRes.headers;
headers['Content-Disposition'] = 'attachment; filename="{0}"'.format(req.asset.originalName);
headers['Content-Type'] = req.asset.clientReportedMimeType;
headers['Content-Length'] = req.asset.size;
res.writeHead(newRes.statusCode, headers);
newRes.pipe(res);
}).on('error', function (err) {
debug('Streaming error: %s', err);
res.statusCode = 500;
res.end();
});

req.pipe(newReq);
req.pipe(newReq);
};

module.exports.getAssetMetadata = function getAssetMetadata(req, res) {
res.json(req.asset);
module.exports.getAssetMetadata = function getAssetMetadata (req, res) {
res.json(req.asset);
};

/**
* @param {ExpressRequest} req
* @param res
*/
module.exports.deleteAsset = function deleteAsset(req, res) {
serviceAsset.deleteAsset(req.service, req.storage, req.asset)
.then((result) => helpers.json(res, result))
.catch((error) => helpers.error(res, error));
module.exports.deleteAsset = function deleteAsset (req, res) {
serviceAsset.deleteAsset(req.service, req.storage, req.asset)
.then((result) => helpers.json(res, result))
.catch((error) => helpers.error(res, error));
};
33 changes: 16 additions & 17 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,22 @@ const format = require('string-format');
format.extend(String.prototype);

class AssetsService extends CampsiService {

initialize() {
this.collection = this.db.collection('assets.{0}'.format(this.path));
this.router.use((req, res, next) => {
req.service = this;
next();
});
this.router.param('asset', param.attachAsset);
this.router.param('asset', param.attachStorage);
this.router.post('/', multer().array('file'), handlers.postAssets);
this.router.get('/', handlers.getAssets);
this.router.get('/local/*', handlers.sendLocalFile);
this.router.get('/:asset/metadata', handlers.getAssetMetadata);
this.router.get('/:asset', handlers.streamAsset);
this.router.delete('/:asset', handlers.deleteAsset);
return super.initialize();
}
initialize () {
this.collection = this.db.collection('assets.{0}'.format(this.path));
this.router.use((req, res, next) => {
req.service = this;
next();
});
this.router.param('asset', param.attachAsset);
this.router.param('asset', param.attachStorage);
this.router.post('/', multer().array('file'), handlers.postAssets);
this.router.get('/', handlers.getAssets);
this.router.get('/local/*', handlers.sendLocalFile);
this.router.get('/:asset/metadata', handlers.getAssetMetadata);
this.router.get('/:asset', handlers.streamAsset);
this.router.delete('/:asset', handlers.deleteAsset);
return super.initialize();
}
}

AssetsService.LocalAssetStorage = require('./storages/local');
Expand Down
36 changes: 18 additions & 18 deletions lib/param.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,25 @@ const createObjectID = require('campsi/lib/modules/createObjectID');
const debug = require('debug')('campsi:services:assets');

module.exports.attachAsset = function (req, res, next, id) {
req.service.collection.findOne({_id: createObjectID(id)}).then((asset) => {
if (!asset) {
return helpers.notFound(res);
}
req.asset = asset;
next();
}).catch((err) => {
debug('Finding asset error: %s', err);
helpers.notFound(res);
});
req.service.collection.findOne({_id: createObjectID(id)}).then((asset) => {
if (!asset) {
return helpers.notFound(res);
}
req.asset = asset;
next();
}).catch((err) => {
debug('Finding asset error: %s', err);
helpers.notFound(res);
});
};

module.exports.attachStorage = function (req, res, next) {
req.storage = req.service.options.storages[req.asset.storage];
if (!req.storage) {
return helpers.error(res, {
message: 'undefined storage',
asset: req.asset
});
}
next();
req.storage = req.service.options.storages[req.asset.storage];
if (!req.storage) {
return helpers.error(res, {
message: 'undefined storage',
asset: req.asset
});
}
next();
};
Loading

0 comments on commit a273d66

Please sign in to comment.