Skip to content

Commit

Permalink
Reconfiguring prettier and eslint
Browse files Browse the repository at this point in the history
  • Loading branch information
baamenabar committed Feb 12, 2019
1 parent 15ab6d9 commit 3b2a6ef
Show file tree
Hide file tree
Showing 7 changed files with 97 additions and 73 deletions.
2 changes: 1 addition & 1 deletion .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,4 @@ trim_trailing_whitespace = false

[*.yml]
indent_style = space
indent_size = 2
indent_size = 4
29 changes: 27 additions & 2 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,28 @@
module.exports = {
"extends": "airbnb-base"
};
extends: 'airbnb-base',
parserOptions: {
ecmaVersion: '2018',
},
env: {
browser: false,
node: true,
commonjs: true,
mocha: true,
},
rules: {
indent: ['error', 4],
'linebreak-style': ['error', 'unix'],
'consistent-return': 'off',
'max-len': [
'error',
{
code: 100,
comments: 160,
},
],
'prefer-destructuring': 'off',
'prefer-template': 'off',
'comma-dangle': ['error', 'only-multiline'],
'arrow-parens': 'off',
},
};
6 changes: 0 additions & 6 deletions .prettierrc

This file was deleted.

6 changes: 6 additions & 0 deletions .prettierrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"tabWidth": 4,
"printWidth": 100,
"singleQuote": true,
"trailingComma": "es5"
}
67 changes: 33 additions & 34 deletions server/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const morgan = require('morgan');
const glob = require('glob');
const fs = require('fs');
const fse = require('fs-extra');
const urlParse = require('url').parse;

const stats = require('./stat');
const mimetypes = require('./mimetypes');
Expand All @@ -16,8 +17,8 @@ const API_MEDIA_URL = process.env.API_MEDIA_URL;
const STORAGE_FOLDER = process.env.STORAGE_FOLDER;

const contentTypes = {
appJson: "application/json",
multipart: "multipart/form-data;",
appJson: 'application/json',
multipart: 'multipart/form-data;',
};

const upHandler = multer({
Expand All @@ -26,23 +27,25 @@ const upHandler = multer({
const extension = mimetypes.getExtensionFromAcceptedMimeType(file.mimetype);

// we store the extension property in the file object
// eslint-disable-next-line no-param-reassign
file.extension = extension;

// for now we just validate if it is one of the expected filetypes.
const isValidFile = !!extension;

cb(null, isValidFile);

// If it's not a valid file, nothing will stop, multer just won't save the file, express will happyly continue it's flow,
},
storage: multer.diskStorage({
destination: (req, file, cb) => {

let error = null;
// if it is not a dir, it's trying to post to a file... crazy
if (!stats.isDirectorySync(req.fsPath)) {
error = {
error: 409,
message: 'ERROR: You can not POST to a file, only a folder. Go home, you crazy.'
message: `ERROR: You can not POST to a file, only a folder.
Go home, you crazy.`,
};
return req.next(error);
}
Expand All @@ -64,7 +67,7 @@ const upHandler = multer({

/** configure CORS */
const originsWhitelist = [
'http://localhost:4200', //this is my front-end url for development
'http://localhost:4200', // this is my front-end url for development
'http://no.clue.yet',
];
const corsOptions = {
Expand Down Expand Up @@ -104,7 +107,7 @@ app.all(API_MEDIA_URL + '*', (req, res) => {

app.post(API_MEDIA_URL + '*', upHandler.single('uploaded_file'), (req, res) => {
// If this is just regular json skip this and go on to the next middleware
if (req.headers["content-type"] === contentTypes.appJson) {
if (req.headers['content-type'] === contentTypes.appJson) {
return req.next();
}

Expand All @@ -114,13 +117,11 @@ app.post(API_MEDIA_URL + '*', upHandler.single('uploaded_file'), (req, res) => {
error: 422,
message: 'ERROR: The uploaded file must be an image',
});
} else {
return res.status(201).json({});
}
return res.status(201).json({});
});

app.get(API_MEDIA_URL + '*', (req, res) => {

const fsPath = req.fsPath;
// if it is not a dir, get the file data
if (!stats.isDirectorySync(fsPath)) {
Expand All @@ -138,27 +139,24 @@ app.get(API_MEDIA_URL + '*', (req, res) => {
maskedPath = !maskedPath || maskedPath.substr(-1) === '/' ? maskedPath : maskedPath + '/';

glob(
maskedPath + '*', {
maskedPath + '*',
{
cwd: STORAGE_FOLDER,
},
(err, files) => {
res.status(200).json(
files
.map(file => {
const relativeStoragePath = STORAGE_FOLDER + file;
return stats.fileInfo(relativeStoragePath);
})
.filter((file) => {
return mimetypes.isListableMimeType(file.mimetype);
})
.map((file) => {
const relativeStoragePath = STORAGE_FOLDER + file;
return stats.fileInfo(relativeStoragePath);
})
.filter(file => mimetypes.isListableMimeType(file.mimetype))
);
}
);
});

app.post(API_MEDIA_URL + '*', (req, res) => {
console.log('2. ---- posting to media path: ', req.url);

// if it is a dir
let maskedPath = req.maskedPath;
// add trailing slash if missing
Expand All @@ -168,12 +166,12 @@ app.post(API_MEDIA_URL + '*', (req, res) => {
if (!req.body.name) {
res.status(400).json({
error: 400,
message: 'ERROR: missing "name" attribute in the post data.'
})
message: 'ERROR: missing "name" attribute in the post data.',
});
return;
}

const newFolderName = require('url').parse(req.body.name).pathname;
const newFolderName = urlParse(req.body.name).pathname;

// we only allow the creation of one folder, not nested ones.
if (newFolderName.indexOf('/') > -1) {
Expand Down Expand Up @@ -202,53 +200,54 @@ app.post(API_MEDIA_URL + '*', (req, res) => {

res.status(201).json({
name: newFolderName,
})
return;
});
});

app.delete(API_MEDIA_URL + '*', (req, res) => {
console.log('3. ---- delete media path: ', req.url);

let maskedPath = req.maskedPath;
const maskedPath = req.maskedPath;

// if the path is the media root, it should not be allowed to delete
if (!maskedPath) {
res.status(405).json({
error: 405,
message: 'Method (DELETE) not alowed for this route.'
})
message: 'Method (DELETE) not alowed for this route.',
});
return;
}

const fsPath = req.fsPath;
// if it is not a dir, check the filetype is listable (and deletable)
if (!stats.isDirectorySync(fsPath)) { // this is a file
if (!stats.isDirectorySync(fsPath)) {
// this is a file
if (mimetypes.isListableFileType(fsPath)) {
fse.removeSync(fsPath);
res.status(200).json({
name: maskedPath
name: maskedPath,
});
} else {
// then this is not a file suposed to be seen
res.status(404).json();
}
} else { // this is a folder
} else {
// this is a folder
fse.removeSync(fsPath);
res.status(200).json({
name: maskedPath
name: maskedPath,
});
}
});

// here we pass unhandled errors (like from multer)
// eslint-disable-next-line no-unused-vars
app.use((err, req, res, next) => {
if (err && err.error) {
res.status(err.error).json(err);
}
})
});

if (!module.parent) {
app.listen(3000);
}
module.exports = app;
// eslint-disable-next-line no-console
console.log('Listening on port 3000');
16 changes: 8 additions & 8 deletions server/mimetypes.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,27 +13,27 @@ const uploadableTypes = {
* This returns an extension for a given filetype, if it's on the list of accepted types
* @param {string} mimetype
*/
const getExtensionFromAcceptedMimeType = mimetype => {
const getExtensionFromAcceptedMimeType = (mimetype) => {
const extension = Object.getOwnPropertyNames(uploadableTypes).filter(
type => uploadableTypes[type] === mimetype
);
//console.log("mime-type:", mimetype, extension);
// console.log("mime-type:", mimetype, extension);
return extension.length ? extension[0] : '';
};

const isListableFileType = path => {
const isListableFileType = (path) => {
const result = !!getExtensionFromAcceptedMimeType(stats.getMimeTypeAndExtension(path).mimetype);

return !!result;
}
};

const isListableMimeType = mimetype => {
return Object.getOwnPropertyNames(uploadableTypes).some(extension => uploadableTypes[extension] === mimetype);
}
const isListableMimeType = mimetype => Object.getOwnPropertyNames(uploadableTypes).some(
extension => uploadableTypes[extension] === mimetype
);

module.exports = {
getExtensionFromAcceptedMimeType,
isListableFileType,
isListableMimeType,
uploadableTypes,
}
};
44 changes: 22 additions & 22 deletions server/stat.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
/* eslint-disable no-unused-vars */
/* eslint-disable camelcase */
const fs = require('fs');
const path = require('path')
const path = require('path');
const fsPromises = require('fs').promises;
const mime = require('mime');

Expand All @@ -16,31 +18,31 @@ function isErrorNotFound(err) {
/**
* The good old synchronous check to see if a path results in a folder.
*
* @param {string} path
* @param {string} filePath
* @returns {boolean}
*/
function isDirectory_sync(path) {
function isDirectory_sync(filePath) {
try {
const stat = fs.statSync(path);
const stat = fs.statSync(filePath);
return stat.isDirectory();
} catch (err) {
// if it's simply a not found error
if (isErrorNotFound(err)) {
return false;
}
//othewise throw the error
// othewise throw the error
throw err;
}
}

/**
* Async + callback version of the check to see if a path resolves to a folder
*
* @param {string} path : does this resolve to a dir?
* @param {string} filePath : does this resolve to a dir?
* @param {Function} callback : this callback gets called with the result (bool)
*/
function isDirectory_callback(path, callback) {
fs.stat(path, (err, stat) => {
function isDirectory_callback(filePath, callback) {
fs.stat(filePath, (err, stat) => {
if (err) {
const errorToReturn = isErrorNotFound(err) ? undefined : err;
callback(errorToReturn, false);
Expand All @@ -53,15 +55,13 @@ function isDirectory_callback(path, callback) {
/**
* Promise based async check if a path resolves to a dir
*
* @param {string} path
* @param {string} filePath
* @returns {Promise}
*/
function isDirectory_promise(path) {
function isDirectory_promise(filePath) {
return fsPromises
.stat(path)
.then(fsStat => {
return fsStat.isDirectory();
})
.stat(filePath)
.then(fsStat => fsStat.isDirectory())
.catch(err => {
if (isErrorNotFound(err)) {
return false;
Expand All @@ -73,12 +73,12 @@ function isDirectory_promise(path) {
/**
* Async awaited version of the check if a path resolves to a dir
*
* @param {string} path
* @param {string} filePath
* @returns {Promise}
*/
async function isDirectory_asyncAwait(path) {
async function isDirectory_asyncAwait(filePath) {
// the result can be either false (from the caught error) or it can be an fs.stats object
const result = await fsPromises.stat(path).catch(err => {
const result = await fsPromises.stat(filePath).catch(err => {
if (isErrorNotFound(err)) {
return false;
}
Expand All @@ -95,15 +95,15 @@ async function isDirectory_asyncAwait(path) {
/**
* Get mime and extension for the filetype of a path.
*
* @param {string} path
* @returns {mimetype: string, extension: string}
* @param {string} filePath
* @returns {object} {mimetype: string, extension: string}
*/
function getMimeTypeAndExtension(path) {
let type = mime.getType(path);
function getMimeTypeAndExtension(filePath) {
let type = mime.getType(filePath);
if (type === null) {
// if not recognized and not a directory, we treat it as txt/plain
// @todo: try to recognize with the file buffer.
type = isDirectory_sync(path) ? 'DIRECTORY' : 'text/plain';
type = isDirectory_sync(filePath) ? 'DIRECTORY' : 'text/plain';
}
let extension = mime.getExtension(type);
extension = extension === 'jpeg' ? 'jpg' : extension;
Expand Down

0 comments on commit 3b2a6ef

Please sign in to comment.