From 256f9f4843a4ff6085413febe66a07efa58f277b Mon Sep 17 00:00:00 2001 From: apostolof Date: Thu, 4 Feb 2021 22:48:51 +0200 Subject: [PATCH] refactor: modify provider service to Promise-based --- .../concordia-contracts-provider/package.json | 1 + .../src/controllers/download.js | 55 +++++++++++-------- .../src/controllers/upload.js | 29 ++++------ .../src/middleware/upload.js | 2 +- .../src/routes/web.js | 5 +- yarn.lock | 5 ++ 6 files changed, 53 insertions(+), 44 deletions(-) diff --git a/packages/concordia-contracts-provider/package.json b/packages/concordia-contracts-provider/package.json index 7bdc166..9c2234e 100755 --- a/packages/concordia-contracts-provider/package.json +++ b/packages/concordia-contracts-provider/package.json @@ -12,6 +12,7 @@ "cors": "^2.8.5", "esm": "~3.2.25", "express": "^4.17.1", + "express-async-handler": "^1.1.4", "lodash": "^4.17.20", "multer": "^1.4.2", "multiparty": "^4.2.2" diff --git a/packages/concordia-contracts-provider/src/controllers/download.js b/packages/concordia-contracts-provider/src/controllers/download.js index fa77b78..baa8151 100755 --- a/packages/concordia-contracts-provider/src/controllers/download.js +++ b/packages/concordia-contracts-provider/src/controllers/download.js @@ -1,31 +1,38 @@ -import * as fs from 'fs'; +import { promises as fs } from 'fs'; import path from 'path'; import { getStorageLocation, getTagsDirectory } from '../utils/storageUtils'; -const downloadContracts = async (req, res) => { - const { params: { hash: hashOrTag } } = req; - let directoryPath = getStorageLocation(hashOrTag); - - if (!fs.existsSync(directoryPath)) { - const tagsDirectory = getTagsDirectory(); - - if (fs.existsSync(tagsDirectory)) { - const tagFilePath = path.join(tagsDirectory, hashOrTag); - const tagReference = fs.readFileSync(tagFilePath, 'utf-8'); - - directoryPath = getStorageLocation(tagReference); - } - } +const readContractFilesToArray = (contractsDirectoryPath) => fs + .readdir(contractsDirectoryPath) + .then((contractFilenames) => contractFilenames + .map((contractFilename) => fs + .readFile(path.join(`${contractsDirectoryPath}/${contractFilename}`), 'utf-8') + .then((rawContractData) => JSON.parse(rawContractData)))) + .then((contractObjectPromises) => Promise.all([...contractObjectPromises])); - const contracts = []; - - fs.readdirSync(directoryPath).forEach((contractFilename) => { - const rawContractData = fs.readFileSync(path.join(`${directoryPath}/${contractFilename}`), 'utf-8'); - const contractJson = JSON.parse(rawContractData); - contracts.push(contractJson); - }); - - res.send(contracts); +const downloadContracts = async (req, res) => { + const { params: { hash: identifier } } = req; + const hashBasedDirectoryPath = getStorageLocation(identifier); + + return fs.access(hashBasedDirectoryPath) + .then(() => readContractFilesToArray(hashBasedDirectoryPath)) + .catch(() => { + const tagsDirectory = getTagsDirectory(); + + return fs + .access(tagsDirectory) + .then(() => { + const tagFilePath = path.join(tagsDirectory, identifier); + + return fs.readFile(tagFilePath, 'utf-8') + .then((tagReference) => { + const tagBasedDirectoryPath = getStorageLocation(tagReference); + + return readContractFilesToArray(tagBasedDirectoryPath); + }); + }); + }).then((contracts) => res.send(contracts)) + .catch(() => Promise.reject(new Error(`No contracts version or tag found for ${identifier}.`))); }; export default downloadContracts; diff --git a/packages/concordia-contracts-provider/src/controllers/upload.js b/packages/concordia-contracts-provider/src/controllers/upload.js index 346c567..894aa40 100755 --- a/packages/concordia-contracts-provider/src/controllers/upload.js +++ b/packages/concordia-contracts-provider/src/controllers/upload.js @@ -1,5 +1,5 @@ import path from 'path'; -import fs from 'fs'; +import { promises as fs } from 'fs'; import upload from '../middleware/upload'; import { getTagsDirectory } from '../utils/storageUtils'; @@ -7,31 +7,26 @@ const addOrTransferTag = (tag, hash) => { const tagsDirectory = getTagsDirectory(); const tagFilePath = path.join(tagsDirectory, tag); - fs.mkdirSync(tagsDirectory, { recursive: true }); - fs.writeFileSync(tagFilePath, hash); + return fs + .mkdir(tagsDirectory, { recursive: true }) + .then(() => fs.writeFile(tagFilePath, hash, 'utf-8')); }; -const uploadContracts = async (req, res) => { - try { - await upload(req, res); +const uploadContracts = async (req, res) => upload(req, res) + .then(() => { + if (req.files.length <= 0) { + return Promise.reject(new Error('You must select at least 1 file.')); + } const { body: { tag } } = req; const { params: { hash } } = req; if (tag) { - addOrTransferTag(tag, hash); - } - - if (req.files.length <= 0) { - return res.send('You must select at least 1 file.'); + return addOrTransferTag(tag, hash) + .then(() => res.send('Files have been uploaded and tagged.')); } return res.send('Files have been uploaded.'); - } catch (error) { - console.log(error); - - return res.send(`Error when trying upload many files: ${error}`); - } -}; + }); export default uploadContracts; diff --git a/packages/concordia-contracts-provider/src/middleware/upload.js b/packages/concordia-contracts-provider/src/middleware/upload.js index c55af11..67ce0b6 100755 --- a/packages/concordia-contracts-provider/src/middleware/upload.js +++ b/packages/concordia-contracts-provider/src/middleware/upload.js @@ -16,7 +16,7 @@ const storage = multer.diskStorage({ if (match.indexOf(file.mimetype) === -1) { const message = `${file.originalname} is invalid. Only JSON files are accepted.`; - return callback(message, null); + callback(message, null); } const filename = `${file.originalname}`; diff --git a/packages/concordia-contracts-provider/src/routes/web.js b/packages/concordia-contracts-provider/src/routes/web.js index 5bdd4fb..61921f4 100755 --- a/packages/concordia-contracts-provider/src/routes/web.js +++ b/packages/concordia-contracts-provider/src/routes/web.js @@ -1,12 +1,13 @@ import express from 'express'; +import asyncHandler from 'express-async-handler'; import downloadContracts from '../controllers/download'; import uploadContracts from '../controllers/upload'; const router = express.Router(); const routes = (app) => { - router.get('/contracts/:hash', downloadContracts); - router.post('/contracts/:hash', uploadContracts); + router.get('/contracts/:hash', asyncHandler(downloadContracts)); + router.post('/contracts/:hash', asyncHandler(uploadContracts)); return app.use('/', router); }; diff --git a/yarn.lock b/yarn.lock index 5123b75..5fe663c 100644 --- a/yarn.lock +++ b/yarn.lock @@ -6638,6 +6638,11 @@ explain-error@^1.0.4: resolved "https://registry.yarnpkg.com/explain-error/-/explain-error-1.0.4.tgz#a793d3ac0cad4c6ab571e9968fbbab6cb2532929" integrity sha1-p5PTrAytTGq1cemWj7urbLJTKSk= +express-async-handler@^1.1.4: + version "1.1.4" + resolved "https://registry.yarnpkg.com/express-async-handler/-/express-async-handler-1.1.4.tgz#225a84908df63b35ae9df94b6f0f1af061266426" + integrity sha512-HdmbVF4V4w1q/iz++RV7bUxIeepTukWewiJGkoCKQMtvPF11MLTa7It9PRc/reysXXZSEyD4Pthchju+IUbMiQ== + express@^4.14.0, express@^4.17.1: version "4.17.1" resolved "https://registry.yarnpkg.com/express/-/express-4.17.1.tgz#4491fc38605cf51f8629d39c2b5d026f98a4c134"