Created
May 23, 2017 00:31
-
-
Save manrueda/291fcb0cfec57446f36a2d6069c0ff59 to your computer and use it in GitHub Desktop.
CRUD over a folder over HTTP
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
const formidable = require('formidable') | |
const fs = require('fs-extra') | |
const path = require('path') | |
module.exports = ({path: _path}) => { | |
fs.ensureDirSync(_path) | |
return async (req, res) => { | |
const method = req.method.toLowerCase() | |
switch (method) { | |
case 'get': | |
await get(_path, req, res) | |
break | |
case 'post': | |
await post(_path, req, res) | |
break | |
case 'delete': | |
await del(_path, req, res) | |
break | |
} | |
jsonResponse(res, {url: req.url}) | |
} | |
function jsonResponse (res, json) { | |
res.writeHead(200, {'content-type': 'application/json'}) | |
res.end(JSON.stringify(json)) | |
} | |
async function get(root, req, res) { | |
const fullPath = req.url.slice(1) | |
const folderName = path.resolve(root, path.dirname(fullPath)) | |
} | |
async function post(root, req, res) { | |
const fullPath = req.url.slice(1) | |
const files = await getFile(req) | |
let folderName | |
if (files.length > 1) { | |
folderName = path.resolve(root, fullPath) | |
} else { | |
folderName = path.resolve(root, path.dirname(fullPath)) | |
} | |
await fs.ensureDir(folderName) | |
if (files.length > 1) { | |
for (let file of files) { | |
await fs.move(file.path, path.resolve(folderName, file.name)) | |
} | |
} else { | |
await fs.move(files[0].path, path.resolve(folderName, path.basename(fullPath))) | |
} | |
} | |
async function del(root, req, res) { | |
const fullPath = req.url.slice(1) | |
const folderName = path.resolve(root, path.dirname(fullPath)) | |
} | |
function getFile (req) { | |
return new Promise((resolve, reject) => { | |
const form = new formidable.IncomingForm() | |
form.maxFieldsSize = 100 * 1024 * 1024 | |
form.parse(req, (err, fields, files) => { | |
if (err) { | |
reject(err) | |
} else { | |
resolve(Object.keys(files).map(k => files[k])) | |
} | |
}) | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment