* Updated eslint-plugin-import dev dependency.

* Added 2 new ESLint rules: "prefer-const" and "object-shorthand".

* Refactor all JS files to follow the new ESLint rules.

* Refactored all instances of for-i into for-of wherever applicable.
This commit is contained in:
Bobby Wibowo 2018-04-05 17:52:57 +07:00
parent 0f3551c3bd
commit b1dbb931c1
No known key found for this signature in database
GPG Key ID: 51C3A1E1E22D26CF
13 changed files with 72 additions and 70 deletions

View File

@ -29,8 +29,8 @@ albumsController.list = async (req, res, next) => {
return res.json({ success: true, albums })
}
let ids = []
for (let album of albums) {
const ids = []
for (const album of albums) {
album.date = utils.getPrettyDate(new Date(album.timestamp * 1000))
album.identifier = `${albumDomain}/a/${album.identifier}`
@ -40,9 +40,9 @@ albumsController.list = async (req, res, next) => {
const files = await db.table('files').whereIn('albumid', ids).select('albumid')
const albumsCount = {}
for (let id of ids) { albumsCount[id] = 0 }
for (let file of files) { albumsCount[file.albumid] += 1 }
for (let album of albums) { album.files = albumsCount[album.id] }
for (const id of ids) { albumsCount[id] = 0 }
for (const file of files) { albumsCount[file.albumid] += 1 }
for (const album of albums) { album.files = albumsCount[album.id] }
return res.json({ success: true, albums })
}
@ -171,7 +171,7 @@ albumsController.get = async (req, res, next) => {
const title = album.name
const files = await db.table('files').select('name').where('albumid', album.id).orderBy('id', 'DESC')
for (let file of files) {
for (const file of files) {
file.file = `${config.domain}/${file.name}`
const ext = path.extname(file.name).toLowerCase()
@ -208,9 +208,9 @@ albumsController.generateZip = async (req, res, next) => {
if (files.length === 0) { return res.json({ success: false, description: 'There are no files in the album.' }) }
const zipPath = path.join(__dirname, '..', config.uploads.folder, 'zips', `${album.identifier}.zip`)
let archive = new Zip()
const archive = new Zip()
for (let file of files) {
for (const file of files) {
try {
// const exists = fs.statSync(path.join(__dirname, '..', config.uploads.folder, file.name))
archive.file(file.name, fs.readFileSync(path.join(__dirname, '..', config.uploads.folder, file.name)))

View File

@ -4,7 +4,7 @@ const bcrypt = require('bcrypt')
const randomstring = require('randomstring')
const utils = require('./utilsController.js')
let authController = {}
const authController = {}
authController.verify = async (req, res, next) => {
const username = req.body.username
@ -60,12 +60,12 @@ authController.register = async (req, res, next) => {
}
const token = randomstring.generate(64)
await db.table('users').insert({
username: username,
username,
password: hash,
token: token,
token,
enabled: 1
})
return res.json({ success: true, token: token })
return res.json({ success: true, token })
})
}
@ -73,7 +73,7 @@ authController.changePassword = async (req, res, next) => {
const user = await utils.authorize(req, res)
if (!user) { return }
let password = req.body.password
const password = req.body.password
if (password === undefined) { return res.json({ success: false, description: 'No password provided.' }) }
if (password.length < 6 || password.length > 64) {
@ -105,7 +105,7 @@ authController.changeFileLength = async (req, res, next) => {
const user = await utils.authorize(req, res)
if (!user) { return }
let fileLength = parseInt(req.body.fileLength)
const fileLength = parseInt(req.body.fileLength)
if (fileLength === undefined) { return res.json({ success: false, description: 'No file name length provided.' }) }
if (isNaN(fileLength)) { return res.json({ success: false, description: 'File name length is not a valid number.' }) }

View File

@ -18,7 +18,7 @@ const chunksDir = path.join(uploadDir, 'chunks')
const maxSizeBytes = parseInt(config.uploads.maxSize) * 1000000
const storage = multer.diskStorage({
destination: function (req, file, cb) {
destination (req, file, cb) {
// If chunked uploads is disabled or the uploaded file is not a chunk
if (!chunkedUploads || (req.body.uuid === undefined && req.body.chunkindex === undefined)) {
return cb(null, uploadDir)
@ -40,7 +40,7 @@ const storage = multer.diskStorage({
})
})
},
filename: function (req, file, cb) {
filename (req, file, cb) {
const extension = path.extname(file.originalname)
// If chunked uploads is disabled or the uploaded file is not a chunk
@ -62,7 +62,7 @@ const upload = multer({
limits: {
fileSize: config.uploads.maxSize
},
fileFilter: function (req, file, cb) {
fileFilter (req, file, cb) {
// If there are no blocked extensions
if (config.blockedExtensions === undefined) {
return cb(null, true)
@ -251,8 +251,7 @@ uploadsController.actuallyFinishChunks = async (req, res, user, albumid) => {
let iteration = 0
const infoMap = []
for (let i = 0; i < files.length; i++) {
const file = files[i]
for (const file of files.length) {
const { uuid, count } = file
if (!uuid || !count) { return erred(new Error('Missing UUID and/or chunks count.')) }
@ -336,8 +335,7 @@ uploadsController.writeFilesToDb = async (req, res, user, albumid, infoMap) => {
const files = []
const existingFiles = []
for (let i = 0; i < infoMap.length; i++) {
const info = infoMap[i]
for (const info of infoMap) {
// Check if the file exists by checking hash and size
const hash = crypto.createHash('md5')
const stream = fs.createReadStream(info.path)
@ -389,7 +387,7 @@ uploadsController.writeFilesToDb = async (req, res, user, albumid, infoMap) => {
}
uploadsController.processFilesForDisplay = async (req, res, files, existingFiles, albumid) => {
let basedomain = config.domain
const basedomain = config.domain
if (files.length === 0) {
return res.json({
success: true,
@ -407,12 +405,11 @@ uploadsController.processFilesForDisplay = async (req, res, files, existingFiles
await db.table('files').insert(files)
// Push existing files to array for response
for (let efile of existingFiles) {
for (const efile of existingFiles) {
files.push(efile)
}
for (let i = 0; i < files.length; i++) {
const file = files[i]
for (const file of files) {
const ext = path.extname(file.name).toLowerCase()
if ((config.uploads.generateThumbnails.image && utils.imageExtensions.includes(ext)) || (config.uploads.generateThumbnails.video && utils.videoExtensions.includes(ext))) {
file.thumb = `${basedomain}/thumbs/${file.name.slice(0, -ext.length)}.png`
@ -528,10 +525,10 @@ uploadsController.list = async (req, res) => {
.select('id', 'albumid', 'timestamp', 'name', 'userid', 'size')
const albums = await db.table('albums')
let basedomain = config.domain
let userids = []
const basedomain = config.domain
const userids = []
for (let file of files) {
for (const file of files) {
file.file = `${basedomain}/${file.name}`
file.date = new Date(file.timestamp * 1000)
file.date = utils.getPrettyDate(file.date)
@ -540,7 +537,7 @@ uploadsController.list = async (req, res) => {
file.album = ''
if (file.albumid !== undefined) {
for (let album of albums) {
for (const album of albums) {
if (file.albumid === album.id) {
file.album = album.name
}
@ -554,7 +551,7 @@ uploadsController.list = async (req, res) => {
}
}
let ext = path.extname(file.name).toLowerCase()
const ext = path.extname(file.name).toLowerCase()
if ((config.uploads.generateThumbnails.image && utils.imageExtensions.includes(ext)) || (config.uploads.generateThumbnails.video && utils.videoExtensions.includes(ext))) {
file.thumb = `${basedomain}/thumbs/${file.name.slice(0, -ext.length)}.png`
}
@ -567,8 +564,8 @@ uploadsController.list = async (req, res) => {
if (userids.length === 0) { return res.json({ success: true, files }) }
const users = await db.table('users').whereIn('id', userids)
for (let dbUser of users) {
for (let file of files) {
for (const dbUser of users) {
for (const file of files) {
if (file.userid === dbUser.id) {
file.username = dbUser.username
}

View File

@ -62,7 +62,7 @@ utilsController.generateThumbs = (file, basedomain) => {
return
}
let thumbname = path.join(__dirname, '..', config.uploads.folder, 'thumbs', file.name.slice(0, -ext.length) + '.png')
const thumbname = path.join(__dirname, '..', config.uploads.folder, 'thumbs', file.name.slice(0, -ext.length) + '.png')
fs.access(thumbname, error => {
if (error && error.code === 'ENOENT') {
if (isVideoExt) {
@ -75,7 +75,7 @@ utilsController.generateThumbs = (file, basedomain) => {
})
.on('error', error => console.log('Error - ', error.message))
} else if (isImageExt) {
let size = {
const size = {
width: 200,
height: 200
}

View File

@ -1,4 +1,4 @@
let init = function (db) {
const init = function (db) {
// Create the tables we need to store galleries and files
db.schema.hasTable('albums').then(exists => {
if (!exists) {

View File

@ -25,7 +25,7 @@ safe.engine('handlebars', exphbs({ defaultLayout: 'main' }))
safe.set('view engine', 'handlebars')
safe.enable('view cache')
let limiter = new RateLimit({ windowMs: 5000, max: 2 })
const limiter = new RateLimit({ windowMs: 5000, max: 2 })
safe.use('/api/login/', limiter)
safe.use('/api/register/', limiter)
@ -47,15 +47,15 @@ safe.use('/', express.static('./public', { setHeaders }))
safe.use('/', album)
safe.use('/api', api)
for (let page of config.pages) {
for (const page of config.pages) {
let root = './pages/'
if (fs.existsSync(`./pages/custom/${page}.html`)) {
root = './pages/custom/'
}
if (page === 'home') {
safe.get('/', (req, res, next) => res.sendFile(`${page}.html`, { root: root }))
safe.get('/', (req, res, next) => res.sendFile(`${page}.html`, { root }))
} else {
safe.get(`/${page}`, (req, res, next) => res.sendFile(`${page}.html`, { root: root }))
safe.get(`/${page}`, (req, res, next) => res.sendFile(`${page}.html`, { root }))
}
}

View File

@ -37,7 +37,7 @@
"devDependencies": {
"eslint": "^4.19.1",
"eslint-config-standard": "^11.0.0",
"eslint-plugin-import": "^2.9.0",
"eslint-plugin-import": "^2.10.0",
"eslint-plugin-node": "^6.0.1",
"eslint-plugin-promise": "^3.7.0",
"eslint-plugin-standard": "^3.0.1"
@ -55,6 +55,17 @@
"error",
"all"
],
"prefer-const": [
"error",
{
"destructuring": "any",
"ignoreReadBeforeAssign": false
}
],
"object-shorthand": [
"error",
"always"
],
"quotes": [
"error",
"single"

View File

@ -17,7 +17,7 @@
<script type="text/javascript" src="libs/sweetalert/sweetalert.min.js?v=vvtL7Y3cjD"></script>
<script type="text/javascript" src="libs/axios/axios.min.js?v=vvtL7Y3cjD"></script>
<script type="text/javascript" src="libs/clipboard.js/clipboard.min.js?v=vvtL7Y3cjD"></script>
<script type="text/javascript" src="js/dashboard.js?v=6Zr9q4fQ0o"></script>
<script type="text/javascript" src="js/dashboard.js?v=XW5nYuTStf"></script>
<!-- Open Graph tags -->
<meta property="og:type" content="website" />

View File

@ -17,7 +17,7 @@
<script type="text/javascript" src="libs/dropzone/dropzone.min.js?v=vvtL7Y3cjD"></script>
<script type="text/javascript" src="libs/axios/axios.min.js?v=vvtL7Y3cjD"></script>
<script type="text/javascript" src="libs/clipboard.js/clipboard.min.js?v=vvtL7Y3cjD"></script>
<script type="text/javascript" src="js/home.js?v=6Zr9q4fQ0o"></script>
<script type="text/javascript" src="js/home.js?v=XW5nYuTStf"></script>
<!-- Open Graph tags -->
<meta property="og:type" content="website" />

View File

@ -25,9 +25,7 @@ panel.verifyToken = (token, reloadOnError) => {
reloadOnError = false
}
axios.post('api/tokens/verify', {
token: token
})
axios.post('api/tokens/verify', { token })
.then(response => {
if (response.data.success === false) {
swal({
@ -358,8 +356,8 @@ panel.selectInBetween = (element, lastElement) => {
if (element === lastElement) { return }
if (!panel.checkboxes || !panel.checkboxes.length) { return }
let thisIndex = panel.checkboxes.indexOf(element)
let lastIndex = panel.checkboxes.indexOf(lastElement)
const thisIndex = panel.checkboxes.indexOf(element)
const lastIndex = panel.checkboxes.indexOf(lastElement)
const distance = thisIndex - lastIndex
if (distance >= -1 && distance <= 1) { return }
@ -446,9 +444,7 @@ panel.deleteFile = (id, album, page) => {
}
}).then(value => {
if (!value) { return }
axios.post('api/upload/delete', {
id: id
})
axios.post('api/upload/delete', { id })
.then(response => {
if (response.data.success === false) {
if (response.data.description === 'No token provided') {
@ -599,7 +595,7 @@ panel.addToAlbum = async (ids, album) => {
})
if (!choose) { return }
let albumid = parseInt(panel.selectAlbumContainer.getElementsByTagName('select')[0].value)
const albumid = parseInt(panel.selectAlbumContainer.getElementsByTagName('select')[0].value)
if (isNaN(albumid)) {
return swal('An error occurred!', 'You did not choose an album.', 'error')
}
@ -743,7 +739,7 @@ panel.renameAlbum = id => {
}).then(value => {
if (!value) { return swal.close() }
axios.post('api/albums/rename', {
id: id,
id,
name: value
})
.then(response => {
@ -785,7 +781,7 @@ panel.deleteAlbum = id => {
}).then(value => {
if (!value) { return }
axios.post('api/albums/delete', {
id: id,
id,
purge: value === 'purge'
})
.then(response => {
@ -1091,9 +1087,7 @@ panel.sendNewPassword = (pass, element) => {
panel.setActiveMenu = item => {
const menu = document.getElementById('menu')
const items = menu.getElementsByTagName('a')
for (let i = 0; i < items.length; i++) {
items[i].className = ''
}
for (const item of items) { item.className = '' }
item.className = 'is-active'
}

View File

@ -53,7 +53,7 @@ upload.preparePage = () => {
upload.verifyToken = (token, reloadOnError) => {
if (reloadOnError === undefined) { reloadOnError = false }
axios.post('api/tokens/verify', { token: token })
axios.post('api/tokens/verify', { token })
.then(response => {
if (response.data.success === false) {
swal({
@ -97,10 +97,10 @@ upload.prepareUpload = () => {
if (albums.length === 0) { return }
// Loop through the albums and create an option for each album
for (let i = 0; i < albums.length; i++) {
for (const album of albums) {
const opt = document.createElement('option')
opt.value = albums[i].id
opt.innerHTML = albums[i].name
opt.value = album.id
opt.innerHTML = album.name
select.appendChild(opt)
}
// Display the album selection

View File

@ -5,7 +5,7 @@ const path = require('path')
const utils = require('../controllers/utilsController.js')
routes.get('/a/:identifier', async (req, res, next) => {
let identifier = req.params.identifier
const identifier = req.params.identifier
if (identifier === undefined) {
return res.status(401).json({ success: false, description: 'No identifier provided' })
}
@ -19,10 +19,10 @@ routes.get('/a/:identifier', async (req, res, next) => {
let thumb = ''
const basedomain = config.domain
for (let file of files) {
for (const file of files) {
file.file = `${basedomain}/${file.name}`
let ext = path.extname(file.name).toLowerCase()
const ext = path.extname(file.name).toLowerCase()
if ((config.uploads.generateThumbnails.image && utils.imageExtensions.includes(ext)) || (config.uploads.generateThumbnails.video && utils.videoExtensions.includes(ext))) {
file.thumb = `${basedomain}/thumbs/${file.name.slice(0, -ext.length)}.png`

View File

@ -754,23 +754,23 @@ eslint-import-resolver-node@^0.3.1:
debug "^2.6.9"
resolve "^1.5.0"
eslint-module-utils@^2.1.1:
version "2.1.1"
resolved "https://registry.yarnpkg.com/eslint-module-utils/-/eslint-module-utils-2.1.1.tgz#abaec824177613b8a95b299639e1b6facf473449"
eslint-module-utils@^2.2.0:
version "2.2.0"
resolved "https://registry.yarnpkg.com/eslint-module-utils/-/eslint-module-utils-2.2.0.tgz#b270362cd88b1a48ad308976ce7fa54e98411746"
dependencies:
debug "^2.6.8"
pkg-dir "^1.0.0"
eslint-plugin-import@^2.9.0:
version "2.9.0"
resolved "https://registry.yarnpkg.com/eslint-plugin-import/-/eslint-plugin-import-2.9.0.tgz#26002efbfca5989b7288ac047508bd24f217b169"
eslint-plugin-import@^2.10.0:
version "2.10.0"
resolved "https://registry.yarnpkg.com/eslint-plugin-import/-/eslint-plugin-import-2.10.0.tgz#fa09083d5a75288df9c6c7d09fe12255985655e7"
dependencies:
builtin-modules "^1.1.1"
contains-path "^0.1.0"
debug "^2.6.8"
doctrine "1.5.0"
eslint-import-resolver-node "^0.3.1"
eslint-module-utils "^2.1.1"
eslint-module-utils "^2.2.0"
has "^1.0.1"
lodash "^4.17.4"
minimatch "^3.0.3"