Browse Source

refactor: modify provider service to Promise-based

develop
Apostolos Fanakis 4 years ago
parent
commit
256f9f4843
  1. 1
      packages/concordia-contracts-provider/package.json
  2. 43
      packages/concordia-contracts-provider/src/controllers/download.js
  3. 29
      packages/concordia-contracts-provider/src/controllers/upload.js
  4. 2
      packages/concordia-contracts-provider/src/middleware/upload.js
  5. 5
      packages/concordia-contracts-provider/src/routes/web.js
  6. 5
      yarn.lock

1
packages/concordia-contracts-provider/package.json

@ -12,6 +12,7 @@
"cors": "^2.8.5", "cors": "^2.8.5",
"esm": "~3.2.25", "esm": "~3.2.25",
"express": "^4.17.1", "express": "^4.17.1",
"express-async-handler": "^1.1.4",
"lodash": "^4.17.20", "lodash": "^4.17.20",
"multer": "^1.4.2", "multer": "^1.4.2",
"multiparty": "^4.2.2" "multiparty": "^4.2.2"

43
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 path from 'path';
import { getStorageLocation, getTagsDirectory } from '../utils/storageUtils'; import { getStorageLocation, getTagsDirectory } from '../utils/storageUtils';
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 downloadContracts = async (req, res) => { const downloadContracts = async (req, res) => {
const { params: { hash: hashOrTag } } = req; const { params: { hash: identifier } } = req;
let directoryPath = getStorageLocation(hashOrTag); const hashBasedDirectoryPath = getStorageLocation(identifier);
if (!fs.existsSync(directoryPath)) { return fs.access(hashBasedDirectoryPath)
.then(() => readContractFilesToArray(hashBasedDirectoryPath))
.catch(() => {
const tagsDirectory = getTagsDirectory(); const tagsDirectory = getTagsDirectory();
if (fs.existsSync(tagsDirectory)) { return fs
const tagFilePath = path.join(tagsDirectory, hashOrTag); .access(tagsDirectory)
const tagReference = fs.readFileSync(tagFilePath, 'utf-8'); .then(() => {
const tagFilePath = path.join(tagsDirectory, identifier);
directoryPath = getStorageLocation(tagReference);
}
}
const contracts = []; return fs.readFile(tagFilePath, 'utf-8')
.then((tagReference) => {
const tagBasedDirectoryPath = getStorageLocation(tagReference);
fs.readdirSync(directoryPath).forEach((contractFilename) => { return readContractFilesToArray(tagBasedDirectoryPath);
const rawContractData = fs.readFileSync(path.join(`${directoryPath}/${contractFilename}`), 'utf-8');
const contractJson = JSON.parse(rawContractData);
contracts.push(contractJson);
}); });
});
res.send(contracts); }).then((contracts) => res.send(contracts))
.catch(() => Promise.reject(new Error(`No contracts version or tag found for ${identifier}.`)));
}; };
export default downloadContracts; export default downloadContracts;

29
packages/concordia-contracts-provider/src/controllers/upload.js

@ -1,5 +1,5 @@
import path from 'path'; import path from 'path';
import fs from 'fs'; import { promises as fs } from 'fs';
import upload from '../middleware/upload'; import upload from '../middleware/upload';
import { getTagsDirectory } from '../utils/storageUtils'; import { getTagsDirectory } from '../utils/storageUtils';
@ -7,31 +7,26 @@ const addOrTransferTag = (tag, hash) => {
const tagsDirectory = getTagsDirectory(); const tagsDirectory = getTagsDirectory();
const tagFilePath = path.join(tagsDirectory, tag); const tagFilePath = path.join(tagsDirectory, tag);
fs.mkdirSync(tagsDirectory, { recursive: true }); return fs
fs.writeFileSync(tagFilePath, hash); .mkdir(tagsDirectory, { recursive: true })
.then(() => fs.writeFile(tagFilePath, hash, 'utf-8'));
}; };
const uploadContracts = async (req, res) => { const uploadContracts = async (req, res) => upload(req, res)
try { .then(() => {
await upload(req, res); if (req.files.length <= 0) {
return Promise.reject(new Error('You must select at least 1 file.'));
}
const { body: { tag } } = req; const { body: { tag } } = req;
const { params: { hash } } = req; const { params: { hash } } = req;
if (tag) { if (tag) {
addOrTransferTag(tag, hash); return addOrTransferTag(tag, hash)
} .then(() => res.send('Files have been uploaded and tagged.'));
if (req.files.length <= 0) {
return res.send('You must select at least 1 file.');
} }
return res.send('Files have been uploaded.'); 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; export default uploadContracts;

2
packages/concordia-contracts-provider/src/middleware/upload.js

@ -16,7 +16,7 @@ const storage = multer.diskStorage({
if (match.indexOf(file.mimetype) === -1) { if (match.indexOf(file.mimetype) === -1) {
const message = `<strong>${file.originalname}</strong> is invalid. Only JSON files are accepted.`; const message = `<strong>${file.originalname}</strong> is invalid. Only JSON files are accepted.`;
return callback(message, null); callback(message, null);
} }
const filename = `${file.originalname}`; const filename = `${file.originalname}`;

5
packages/concordia-contracts-provider/src/routes/web.js

@ -1,12 +1,13 @@
import express from 'express'; import express from 'express';
import asyncHandler from 'express-async-handler';
import downloadContracts from '../controllers/download'; import downloadContracts from '../controllers/download';
import uploadContracts from '../controllers/upload'; import uploadContracts from '../controllers/upload';
const router = express.Router(); const router = express.Router();
const routes = (app) => { const routes = (app) => {
router.get('/contracts/:hash', downloadContracts); router.get('/contracts/:hash', asyncHandler(downloadContracts));
router.post('/contracts/:hash', uploadContracts); router.post('/contracts/:hash', asyncHandler(uploadContracts));
return app.use('/', router); return app.use('/', router);
}; };

5
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" resolved "https://registry.yarnpkg.com/explain-error/-/explain-error-1.0.4.tgz#a793d3ac0cad4c6ab571e9968fbbab6cb2532929"
integrity sha1-p5PTrAytTGq1cemWj7urbLJTKSk= 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: express@^4.14.0, express@^4.17.1:
version "4.17.1" version "4.17.1"
resolved "https://registry.yarnpkg.com/express/-/express-4.17.1.tgz#4491fc38605cf51f8629d39c2b5d026f98a4c134" resolved "https://registry.yarnpkg.com/express/-/express-4.17.1.tgz#4491fc38605cf51f8629d39c2b5d026f98a4c134"

Loading…
Cancel
Save