saweb-api migration

This commit is contained in:
Matias committed 2019-05-24 20:18:11 -03:00
1 parent 23d2094234
commit 8ef729b77f
28 files changed
+876 -79

No files matched your search

+4 -3
View File
@@ -4,6 +4,7 @@ import { ApolloServer } from 'apollo-server-express';
import schema from './schema';
import wrongPreshared from './errors/notAllowed.json';
import db from './db';
import logger from './utils/logger'
const app = express();
@@ -42,12 +43,12 @@ server.applyMiddleware({
});
db.on('error', (err) => {
console.log(err);
logger.error(err);
});
db.once('open', () => {
console.log('Connected to the DB.');
logger.info('Connected to the DB.');
});
app.listen(process.env.PORT, () => {
console.log(`Listening on port ${process.env.PORT}`);
logger.info(`Listening on port ${process.env.PORT}`);
});
+18 -2
View File
@@ -20,6 +20,10 @@ const ecosystemSchema = new Schema({
type: String,
required: true
},
storage: {
type: String,
required: true
},
container: {
type: String,
required: true
@@ -30,13 +34,21 @@ const ecosystemSchema = new Schema({
}
},
bots: [{
repo: {
codeName: {
type: String,
required: true
},
configFile: {
displayName: {
type: String,
required: true
},
repo: {
type: String,
required: false
},
configFile: {
type: String,
required: false
}
}],
plotters: [{
@@ -64,6 +76,10 @@ const ecosystemSchema = new Schema({
type: String,
required: true
},
storage: {
type: String,
required: true
},
container: {
type: String,
required: true
+25 -25
View File
@@ -1,17 +1,11 @@
import { AuthenticationError } from '../../errors';
import { TeamType } from '../types';
import { Ecosystem } from '../../models';
import { TeamInputType } from '../types/input';
import logger from '../../utils/logger';
import { createContainer } from '../../storage/AzureStorage';
import logger from '../../utils/logger'
import { AuthenticationError, WrongArgumentsError } from '../../errors'
import { TeamType } from '../types'
import { Ecosystem } from '../../models'
import { TeamInputType } from '../types/input'
import { createTeam } from '../../storage/CreateTeam'
import {
GraphQLString
} from 'graphql';
export const args = {
team: { type: TeamInputType },
};
export const args = { team: { type: TeamInputType } }
const resolve = async (parent, { team }, context) => {
logger.debug('addTeam -> Entering Fuction.')
@@ -33,36 +27,42 @@ const resolve = async (parent, { team }, context) => {
userEcosystem.authId = context.userId
}
let containerName = team.codeName
await createContainer(containerName)
// let accessKey = await createPrivateAccessKey()
let accessKey = "test"
for (let i = 0; i < userEcosystem.teams.length; i++) {
const auxTeam = userEcosystem.teams[i];
if (auxTeam.codeName === team.codeName) {
throw new WrongArgumentsError("The team already exist on the user ecosystem.")
}
}
let accessKey = await createTeam(team)
if (!team.host) {
let nodeEndpoint = {
url: process.env.SUPERALGOS_NODE_ENDPOINT,
container: containerName,
container: team.codeName,
accessKey: accessKey,
}
team.host = nodeEndpoint
}
let bots= []
bots.push(team.bot)
team.bots = bots
userEcosystem.teams.push(team)
await userEcosystem.save()
return team
} catch (err) {
logger.error('addTeam -> Error: %s', err.stack)
// throw new ServerError('There has been an error adding the team.')
return 'There has been an error adding the team.'
throw err
}
};
}
const mutation = {
addTeam: {
type: GraphQLString,
type: TeamType,
args,
resolve,
},
};
}
}
export default mutation;
+60
View File
@@ -0,0 +1,60 @@
import logger from '../../utils/logger'
import { AuthenticationError, WrongArgumentsError } from '../../errors'
import { TeamType } from '../types'
import { Ecosystem } from '../../models'
import { TeamInputType } from '../types/input'
import { deleteTeam } from '../../storage/DeleteTeam'
export const args = { team: { type: TeamInputType } }
const resolve = async (parent, { team }, context) => {
logger.debug('deleteTeam -> Entering Fuction.')
if (!context.userId) {
throw new AuthenticationError()
}
try {
let userEcosystem = await Ecosystem.findOne({
authId: context.userId
})
if (!userEcosystem) {
logger.debug('deleteTeam -> Ecosystem not found for the user.')
throw new WrongArgumentsError('The user does not have an ecosystem configured.')
}
let teamFound = false
for (let i = 0; i < userEcosystem.teams.length; i++) {
const auxTeam = userEcosystem.teams[i]
if (auxTeam.codeName === team.codeName) {
logger.debug('deleteTeam -> Team found, removing.')
teamFound = true
await deleteTeam(team)
userEcosystem.teams.splice(i, 1)
await userEcosystem.save()
break
}
}
if (!teamFound) {
throw new WrongArgumentsError('Team was not found on the user ecosystem.')
} else {
return team
}
} catch (err) {
logger.error('deleteTeam -> Error: %s', err.stack)
throw err
}
}
const mutation = {
deleteTeam: {
type: TeamType,
args,
resolve,
}
}
export default mutation;
+2
View File
@@ -3,11 +3,13 @@ import {
} from 'graphql';
import AddTeamMutation from './AddTeam';
import DeleteTeamMutation from './DeleteTeam';
const Mutation = new GraphQLObjectType({
name: 'Mutation',
fields: Object.assign(
AddTeamMutation,
DeleteTeamMutation
),
});
+42
View File
@@ -0,0 +1,42 @@
import logger from '../../utils/logger'
import { Ecosystem } from '../../models'
import { EcosystemType } from '../types'
const args = {}
const resolve = async (parent, args, context) => {
logger.debug('getEcosystem -> Entering Fuction.')
try {
if (!context.userId) {
logger.debug('getEcosystem -> User not logged in, returning default ecosystem.')
let defaultEcosystem = require('../../config/ecosystem.json')
return defaultEcosystem
} else {
let userEcosystem = await Ecosystem.findOne({
authId: context.userId
})
if (!userEcosystem) {
logger.debug('addTeam -> Ecosystem not found for the user, retrieving default.')
let defaultEcosystem = require('../../config/ecosystem.json')
return defaultEcosystem
}
return userEcosystem
}
} catch (err) {
logger.error('getEcosystem -> Error: %s', err.stack)
throw err
}
}
const query = {
getEcosystem: {
type: EcosystemType,
args,
resolve,
}
}
export default query
+33
View File
@@ -0,0 +1,33 @@
import logger from '../../utils/logger'
import { FileInputType } from '../types/input'
import { GraphQLString } from 'graphql'
export const args = { file: { type: FileInputType } }
const resolve = async (parent, { file }, context) => {
logger.debug('getFileContent -> Entering Fuction: ' + file.filePath)
try {
let storage = require('../../storage/providers/AzureStorage') // Default value
if (process.env.STORAGE_PROVIDER === 'Minio') {
storage = require('../storage/providers/MinioStorage')
}
return storage.getFileContentRemote(file.container, file.filePath, file.storage, file.accessKey)
} catch (err) {
logger.error('getFileContent -> Error: %s', err.stack)
throw err
}
}
const query = {
fileContent: {
type: GraphQLString,
args,
resolve,
}
}
export default query
-21
View File
@@ -1,21 +0,0 @@
import { GraphQLList } from 'graphql';
import { TeamType } from '../types';
import { Ecosystem } from '../../models';
import logger from '../../utils/logger'
const args = {};
const resolve = (parent, args, context) => {
logger.debug('Listing teams.')
}
const query = {
teams: {
type: new GraphQLList(TeamType),
args,
resolve,
},
};
export default query;
+4 -2
View File
@@ -2,12 +2,14 @@ import {
GraphQLObjectType,
} from 'graphql';
import TeamsQuery from './Teams';
import EcosystemQuery from './Ecosystem';
import FileContentQuery from './FileContent';
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: Object.assign(
TeamsQuery
EcosystemQuery,
FileContentQuery
),
});
+2
View File
@@ -6,6 +6,8 @@ import {
const BotType = new GraphQLObjectType({
name: 'Bot',
fields: () => ({
codeName: { type: GraphQLString },
displayName: { type: GraphQLString },
repo: { type: GraphQLString },
configFile: { type: GraphQLString }
}),
+2 -1
View File
@@ -1,7 +1,8 @@
import {
GraphQLObjectType,
GraphQLString,
GraphQLID
GraphQLID,
GraphQLList
} from 'graphql';
import { TeamType, EventHostType } from './index';
+2 -1
View File
@@ -1,6 +1,7 @@
import {
GraphQLObjectType,
GraphQLString
GraphQLString,
GraphQLList
} from 'graphql';
import { BotType } from './index';
+17
View File
@@ -0,0 +1,17 @@
import {
GraphQLObjectType,
GraphQLString
} from 'graphql';
const FileType = new GraphQLObjectType({
name: 'File',
fields: () => ({
container: { type: GraphQLString },
filePath: { type: GraphQLString },
storage: { type: GraphQLString },
accessKey: { type: GraphQLString },
fileContent: { type: GraphQLString }
}),
});
export default FileType;
+1
View File
@@ -7,6 +7,7 @@ const HostType = new GraphQLObjectType({
name: 'Host',
fields: () => ({
url: { type: GraphQLString },
storage: { type: GraphQLString },
container: { type: GraphQLString },
accessKey: { type: GraphQLString }
}),
+5 -1
View File
@@ -2,10 +2,14 @@ import TeamType from './Team';
import BotType from './Bot';
import EventHostType from './EventHost';
import HostType from './Host';
import EcosystemType from './Ecosystem';
import FileType from './File';
export {
TeamType,
BotType,
EventHostType,
HostType
HostType,
EcosystemType,
FileType
};
+4 -1
View File
@@ -1,12 +1,15 @@
import {
GraphQLInputObjectType,
GraphQLString
GraphQLString,
GraphQLNonNull
} from 'graphql';
const Type = new GraphQLInputObjectType({
name: 'BotInput',
description: 'Payload for bot input.',
fields: () => ({
codeName: { type: new GraphQLNonNull(GraphQLString) },
displayName: { type: new GraphQLNonNull(GraphQLString) },
repo: { type: GraphQLString },
configFile: { type: GraphQLString }
}),
+19
View File
@@ -0,0 +1,19 @@
import {
GraphQLInputObjectType,
GraphQLString,
GraphQLNonNull
} from 'graphql';
const Type = new GraphQLInputObjectType({
name: 'FileInput',
description: 'Payload for file input.',
fields: () => ({
container: { type: new GraphQLNonNull(GraphQLString) },
filePath: { type: new GraphQLNonNull(GraphQLString) },
storage: { type: new GraphQLNonNull(GraphQLString) },
accessKey: { type: new GraphQLNonNull(GraphQLString) },
fileContent: { type: GraphQLString }
}),
});
export default Type;
+1
View File
@@ -8,6 +8,7 @@ const Type = new GraphQLInputObjectType({
description: 'Payload for host input.',
fields: () => ({
url: { type: GraphQLString },
storage: { type: GraphQLString },
container: { type: GraphQLString },
accessKey: { type: GraphQLString }
}),
+2 -2
View File
@@ -14,8 +14,8 @@ const Type = new GraphQLInputObjectType({
codeName: { type: new GraphQLNonNull(GraphQLString) },
displayName: { type: new GraphQLNonNull(GraphQLString) },
host: { type: HostInputType },
bots: { type: new GraphQLNonNull(new GraphQLList(BotInputType)) },
plotters: { type: new GraphQLList(BotInputType) }
bot: { type: new GraphQLNonNull(BotInputType) },
plotter: { type: BotInputType }
}),
});
+3 -1
View File
@@ -1,9 +1,11 @@
import TeamInputType from './Team'
import BotInputType from './Bot'
import HostInputType from './Host'
import FileInputType from './File'
export {
TeamInputType,
BotInputType,
HostInputType
HostInputType,
FileInputType
};
+60
View File
@@ -0,0 +1,60 @@
import beautify from 'json-beautify'
import logger from '../utils/logger'
export const copyBot = async (storage, teamCodeName, botCodeName, botDisplayName) => {
try {
logger.debug('copyBot started for bot %s', botCodeName)
let containerName = 'aavikings'
let templatePath = 'AAVikings/bots/blumblebee-Trading-Bot'
let config = await storage.getFileContent(containerName, templatePath + '/this.bot.config.json')
let code = await storage.getFileContent(containerName, templatePath + '/Trading-Process/User.Bot.js')
// Change config to adapt the new indicator
let parsedConfig = JSON.parse(config)
parsedConfig.displayName = botDisplayName
parsedConfig.codeName = botCodeName
parsedConfig.devTeam = teamCodeName
parsedConfig.profilePicture = botCodeName + '.png'
parsedConfig.processes[0].statusDependencies[0].devTeam = teamCodeName
parsedConfig.processes[0].statusDependencies[0].bot = botCodeName
parsedConfig.processes[0].statusDependencies[1].devTeam = teamCodeName
parsedConfig.processes[0].statusDependencies[1].bot = 'simulator-' + botCodeName
parsedConfig.processes[0].statusDependencies[2].devTeam = teamCodeName
parsedConfig.processes[0].statusDependencies[2].bot = 'simulator-' + botCodeName
parsedConfig.processes[0].dataDependencies[1].devTeam = teamCodeName
parsedConfig.processes[0].dataDependencies[1].bot = 'simulator-' + botCodeName
parsedConfig.processes[0].dataDependencies[2].devTeam = teamCodeName
parsedConfig.processes[0].dataDependencies[2].bot = 'simulator-' + botCodeName
// Write the new files
let newBotPath = teamCodeName + '/bots/' + botCodeName + '-Trading-Bot'
await storage.writeFileContent(teamCodeName, newBotPath + '/this.bot.config.json', beautify(parsedConfig, null, 2, 80))
await storage.writeFileContent(teamCodeName, newBotPath + '/Trading-Bot/User.Bot.js', code)
logger.debug('copyBot completed for bot %s', botCodeName)
} catch (err) {
logger.error('copyBot error for bot: %s. %s', botCodeName, err)
throw err
}
}
export const removeBot = async (storage, teamCodeName, botCodeName) => {
try {
logger.debug('removeBot started for bot %s', botCodeName)
// Delete bot code
let newBotPath = teamCodeName + '/bots/' + 'bot-' + botCodeName
await storage.deleteBlob(teamCodeName, newBotPath + '/this.bot.config.json')
await storage.deleteBlob(teamCodeName, newBotPath + '/Trading-Bot/User.Bot.js')
logger.debug('removeBot completed for bot %s', botCodeName)
} catch (err) {
logger.error('copyBot error for bot %s: %s', botCodeName, err)
throw err
}
}
+83
View File
@@ -0,0 +1,83 @@
import beautify from 'json-beautify'
import logger from '../utils/logger'
export const copySimulator = async (storage, teamCodeName, botCodeName, botDisplayName) => {
try {
logger.debug('copySimulator started for bot %s', 'simulator-' + botCodeName)
let containerName = 'aamasters'
let templatePath = 'AAMasters/bots/AAJason-Indicator-Bot'
let commons = await storage.getFileContent(containerName, templatePath + '/Commons.js')
let config = await storage.getFileContent(containerName, templatePath + '/this.bot.config.json')
let codeDaily = await storage.getFileContent(containerName, templatePath + '/Multi-Period-Daily/User.Bot.js')
let codeMarket = await storage.getFileContent(containerName, templatePath + '/Multi-Period-Market/User.Bot.js')
// Change config to adapt the new indicator
let newBotCodeName = 'simulator-' + botCodeName
let parsedConfig = JSON.parse(config)
parsedConfig.displayName = 'Simulator ' + botDisplayName
parsedConfig.codeName = newBotCodeName
parsedConfig.devTeam = teamCodeName
parsedConfig.profilePicture = newBotCodeName + '.png'
parsedConfig.processes[0].statusDependencies[0].devTeam = teamCodeName
parsedConfig.processes[0].statusDependencies[0].bot = newBotCodeName
parsedConfig.processes[1].statusDependencies[2].devTeam = teamCodeName
parsedConfig.processes[1].statusDependencies[2].bot = newBotCodeName
//Changing Indicator Output
parsedConfig.products[0].storageAccount = teamCodeName
parsedConfig.products[0].dataSets[0].filePath = teamCodeName + '/' + parsedConfig.codeName + '.1.0/AACloud.1.1/@Exchange/dataSet.V1/Output/Trading-Simulation/Multi-Period-Market/@Period'
parsedConfig.products[0].dataSets[1].filePath = teamCodeName + '/' + parsedConfig.codeName + '.1.0/AACloud.1.1/@Exchange/dataSet.V1/Output/Trading-Simulation/Multi-Period-Daily/@Period/@Year/@Month/@Day'
parsedConfig.products[0].dataSets[1].dataRange.filePath = teamCodeName + '/' + parsedConfig.codeName + '.1.0/AACloud.1.1/@Exchange/dataSet.V1/Output/Trading-Simulation/Multi-Period-Daily'
parsedConfig.products[1].storageAccount = teamCodeName
parsedConfig.products[1].dataSets[0].filePath = teamCodeName + '/' + parsedConfig.codeName + '.1.0/AACloud.1.1/@Exchange/dataSet.V1/Output/Simulation-Conditions/Multi-Period-Market/@Period'
parsedConfig.products[1].dataSets[1].filePath = teamCodeName + '/' + parsedConfig.codeName + '.1.0/AACloud.1.1/@Exchange/dataSet.V1/Output/Simulation-Conditions/Multi-Period-Daily/@Period/@Year/@Month/@Day'
parsedConfig.products[1].dataSets[1].dataRange.filePath = teamCodeName + '/' + parsedConfig.codeName + '.1.0/AACloud.1.1/@Exchange/dataSet.V1/Output/Simulation-Conditions/Multi-Period-Daily'
parsedConfig.products[2].storageAccount = teamCodeName
parsedConfig.products[2].dataSets[0].filePath = teamCodeName + '/' + parsedConfig.codeName + '.1.0/AACloud.1.1/@Exchange/dataSet.V1/Output/Simulation-Strategies/Multi-Period-Market/@Period'
parsedConfig.products[2].dataSets[1].filePath = teamCodeName + '/' + parsedConfig.codeName + '.1.0/AACloud.1.1/@Exchange/dataSet.V1/Output/Simulation-Strategies/Multi-Period-Daily/@Period/@Year/@Month/@Day'
parsedConfig.products[2].dataSets[1].dataRange.filePath = teamCodeName + '/' + parsedConfig.codeName + '.1.0/AACloud.1.1/@Exchange/dataSet.V1/Output/Simulation-Strategies/Multi-Period-Daily'
parsedConfig.products[3].storageAccount = teamCodeName
parsedConfig.products[3].dataSets[0].filePath = teamCodeName + '/' + parsedConfig.codeName + '.1.0/AACloud.1.1/@Exchange/dataSet.V1/Output/Simulation-Trades/Multi-Period-Market/@Period'
parsedConfig.products[3].dataSets[1].filePath = teamCodeName + '/' + parsedConfig.codeName + '.1.0/AACloud.1.1/@Exchange/dataSet.V1/Output/Simulation-Trades/Multi-Period-Daily/@Period/@Year/@Month/@Day'
parsedConfig.products[3].dataSets[1].dataRange.filePath = teamCodeName + '/' + parsedConfig.codeName + '.1.0/AACloud.1.1/@Exchange/dataSet.V1/Output/Simulation-Trades/Multi-Period-Daily'
// Write the new files
let newSimulatorName = 'simulator-' + newBotCodeName + '-Indicator-Bot'
let newSimulatorPath = teamCodeName + '/bots/' + newSimulatorName
await storage.writeFileContent(teamCodeName, newSimulatorPath + '/Commons.js', commons)
await storage.writeFileContent(teamCodeName, newSimulatorPath + '/this.bot.config.json', beautify(parsedConfig, null, 2, 80))
await storage.writeFileContent(teamCodeName, newSimulatorPath + '/Multi-Period-Daily/User.Bot.js', codeDaily)
await storage.writeFileContent(teamCodeName, newSimulatorPath + '/Multi-Period-Market/User.Bot.js', codeMarket)
logger.debug('copySimulator completed for bot %s', newBotCodeName)
} catch (err) {
logger.error('copySimulator error for bot: %s. %s', botCodeName, err)
throw err
}
}
export const removeSimulator = async (storage, teamCodeName, botCodeName) => {
try {
logger.debug('removeSimulator started for bot %s', botCodeName)
// Delete simulator code
let newSimulatorName = 'simulator-' + botCodeName + '-Indicator-Bot'
let newSimulatorPath = teamCodeName + '/bots/' + newSimulatorName
await storage.deleteBlob(teamCodeName, newSimulatorPath + '/Commons.js')
await storage.deleteBlob(teamCodeName, newSimulatorPath + '/this.bot.config.json')
await storage.deleteBlob(teamCodeName, newSimulatorPath + '/Multi-Period-Daily/User.Bot.js')
await storage.deleteBlob(teamCodeName, newSimulatorPath + '/Multi-Period-Market/User.Bot.js')
logger.debug('removeSimulator completed for bot %s', botCodeName)
} catch (err) {
logger.error('copySimulator error for bot %s: %s', botCodeName, err)
throw err
}
}
+27
View File
@@ -0,0 +1,27 @@
import logger from '../utils/logger'
import { copyBot } from './CopyBot'
import { copySimulator } from './CopySimulator'
export const createTeam = async (team) => {
try {
logger.debug('createTeam started for team %s', team.codeName)
let storage = require ('./providers/AzureStorage') // Default value
if (process.env.STORAGE_PROVIDER === 'Minio') {
storage = require ('./providers/MinioStorage')
}
let containerName = team.codeName
await storage.createContainer(containerName)
let accessKey = storage.createPrivateAccessKey(containerName, "WRITE", 365)
await copyBot(storage, team.codeName, team.bot.codeName, team.bot.displayName)
await copySimulator(storage, team.codeName, team.bot.codeName, team.bot.displayName)
return accessKey
} catch (err) {
logger.error('createTeam error for teamCodeName: %s, error: %s', team.bot.codeName, err.stack)
throw err
}
}
+18
View File
@@ -0,0 +1,18 @@
import logger from '../utils/logger'
export const deleteTeam = async (team) => {
try {
logger.debug('deleteTeam started for team %s', team.codeName)
let storage = require ('./providers/AzureStorage') // Default value
if (process.env.STORAGE_PROVIDER === 'Minio') {
storage = require ('./providers/MinioStorage')
}
await storage.deleteContainer(team.codeName)
} catch (err) {
logger.error('deleteTeam error for teamCodeName: %s, error: %s', team.codeName, err.stack)
throw err
}
}
@@ -1,37 +1,49 @@
import logger from '../utils/logger'
const {
import logger from '../../utils/logger'
import {
Aborter,
BlobURL,
BlockBlobURL,
ContainerURL,
ServiceURL,
StorageURL,
SharedKeyCredential
} = require("@azure/storage-blob")
SharedKeyCredential,
AnonymousCredential
} from '@azure/storage-blob'
const AzureServiceURL = () => {
// Enter your storage account name and shared key
const account = process.env.STORAGE_BASE_URL;
const accountKey = process.env.STORAGE_CONNECTION_STRING;
// Use SharedKeyCredential with storage account and account key
const sharedKeyCredential = new SharedKeyCredential(account, accountKey);
const sharedKeyCredential = new SharedKeyCredential(process.env.STORAGE_BASE_URL, process.env.STORAGE_CONNECTION_STRING);
// Use sharedKeyCredential, tokenCredential or anonymousCredential to create a pipeline
const pipeline = StorageURL.newPipeline(sharedKeyCredential);
const pipeline = StorageURL.newPipeline(sharedKeyCredential, {
retryOptions: { maxTries: 10 }
});
// List containers
const serviceURL = new ServiceURL(
// When using AnonymousCredential, following url should include a valid SAS or support public access
`https://${account}.blob.core.windows.net`,
`https://${process.env.STORAGE_BASE_URL}.blob.core.windows.net`,
pipeline
);
logger.info("Connected to te file Storage.")
)
return serviceURL
}
const serviceURL = AzureServiceURL()
export const getFileContentRemote = async (containerName, blobName, storage, accessKey) => {
const pipeline = StorageURL.newPipeline(new AnonymousCredential(), {
retryOptions: { maxTries: 10 }
});
const serviceURLWithAccessKey = new ServiceURL(
`${storage}${accessKey}`,
pipeline
);
const containerURL = ContainerURL.fromServiceURL(serviceURLWithAccessKey, containerName)
const blockBlobURL = BlockBlobURL.fromContainerURL(containerURL, blobName)
let downloadResponse = await blockBlobURL.download(Aborter.none, 0)
return await streamToString(downloadResponse.readableStreamBody)
}
export const getFileContent = async (containerName, blobName) => {
const containerURL = ContainerURL.fromServiceURL(serviceURL, containerName)
const blockBlobURL = BlockBlobURL.fromContainerURL(containerURL, blobName)
@@ -76,12 +88,52 @@ export const createContainer = async (containerName) => {
async function streamToString(readableStream) {
return new Promise((resolve, reject) => {
const chunks = [];
readableStream.on("data", data => {
readableStream.on('data', data => {
chunks.push(data.toString());
});
readableStream.on("end", () => {
resolve(chunks.join(""));
readableStream.on('end', () => {
resolve(chunks.join(''));
});
readableStream.on("error", reject)
readableStream.on('error', reject)
});
}
export const createPrivateAccessKey = (container, type, days) => {
let azure = require('azure-storage');
let blobService = azure.createBlobService(process.env.AZURE_STORAGE_CONNECTION_STRING);
let startDate = new Date();
startDate.setDate(startDate.getDate() - 1);
let expiryDate = new Date(startDate);
expiryDate.setDate(startDate.getDate() + days);
let azurePermissions;
switch (type) {
case 'READ': {
azurePermissions = azure.BlobUtilities.SharedAccessPermissions.READ;
break;
}
case 'WRITE': {
azurePermissions = azure.BlobUtilities.SharedAccessPermissions.WRITE;
break;
}
case 'DELETE': {
azurePermissions = azure.BlobUtilities.SharedAccessPermissions.DELETE;
break;
}
}
let blobName = undefined;
let sharedAccessPolicy = {
AccessPolicy: {
Permissions: azurePermissions,
Start: startDate,
Expiry: expiryDate
}
};
return blobService.generateSharedAccessSignature(container, blobName, sharedAccessPolicy);
}
+2 -2
View File
@@ -13,7 +13,7 @@ const options = {
timestamp: true
},
console: {
level: 'debug',
level: process.env.LOG_LEVEL || 'debug',
handleExceptions: true,
json: false,
colorize: true,
@@ -32,7 +32,7 @@ const logger = createLogger({
)
),
transports: [
new transports.File(options.file),
// new transports.File(options.file),
new transports.Console(options.console)
],
exitOnError: false // do not exit on handled exceptions