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",
"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"

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

29
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;

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

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

5
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);
};

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"
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"

Loading…
Cancel
Save