|
|
@@ -76,6 +76,25 @@ function mapObjToArray(obj, key, value) {
|
|
|
return arr;
|
|
|
}
|
|
|
|
|
|
+function checkBodyPropsExist(props) {
|
|
|
+ return function(req, res, next) {
|
|
|
+ if(! props) {
|
|
|
+ throw new Error('checkBodyPropsExist was called with empty props argument');
|
|
|
+ }
|
|
|
+ if(! req.body) {
|
|
|
+ return res.status(400).send('request doest not have a body: please set "content-type" header to "application/json"');
|
|
|
+ }
|
|
|
+ props = typeof props === 'string' ? [props] : props;
|
|
|
+ for(let p = 0 ; p < props.length ; p++) {
|
|
|
+ const prop = props[p];
|
|
|
+ if(! req.body[prop]) {
|
|
|
+ return res.status(400).send('request body doest not have a `' + prop + '` parameter: please provide it.');
|
|
|
+ }
|
|
|
+ }
|
|
|
+ next();
|
|
|
+ };
|
|
|
+}
|
|
|
+
|
|
|
/**
|
|
|
* Get repo parts
|
|
|
*/
|
|
|
@@ -151,6 +170,38 @@ app.post('/repos', function(req, res) {
|
|
|
|
|
|
});
|
|
|
|
|
|
+app.post('/:repoSlug/examples/:exampleSlug/file',
|
|
|
+ checkRepoExists,
|
|
|
+ checkBodyPropsExist('name'),
|
|
|
+ function(req, res) {
|
|
|
+ const { name } = req.body;
|
|
|
+ const { repoSlug, exampleSlug } = req.params;
|
|
|
+ const re = /^[A-Za-z0-9_\-\.]+$/;
|
|
|
+ const targetDir = examplesDir + '/' + repoSlug + '/' + exampleSlug;
|
|
|
+ const fullPath = targetDir + '/' + name;
|
|
|
+ if(! re.test(name)) {
|
|
|
+ return res.status(400).json('Le paramètre `name` est incorrect: caractères autorisés: lettres, chiffres, _, - et .' );
|
|
|
+ }
|
|
|
+ fs.statAsync(fullPath)
|
|
|
+ // Invert the usual flow of a Promise. fs.stat() fails if file does not exist (which is what we want)
|
|
|
+ // Hence .catch() is a success handler and .then() an error handler (has to rethrow)
|
|
|
+ .catch(err => {
|
|
|
+ return fs.writeFileAsync(fullPath, '')
|
|
|
+ .then(() => res.json({
|
|
|
+ name,
|
|
|
+ path: fullPath
|
|
|
+ }));
|
|
|
+ })
|
|
|
+ .then(stats => {
|
|
|
+ throw new Error('Le fichier `' + name + '` existe déjà !');
|
|
|
+ })
|
|
|
+ .catch(err => {
|
|
|
+ const statusCode = err.message.startsWith('Le fichier') ? 409 : 500;
|
|
|
+ return res.status(statusCode).send(err.message);
|
|
|
+ });
|
|
|
+ }
|
|
|
+);
|
|
|
+
|
|
|
/**
|
|
|
* Create a new example for specified repo
|
|
|
*/
|
|
|
@@ -210,6 +261,9 @@ app.get('/examples/:repoSlug/:slug',
|
|
|
}
|
|
|
);
|
|
|
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
app.get('/menu', (rea, res) => {
|
|
|
res.send(exStore.getMenu());
|
|
|
});
|