i have an azure function with http trigger, then this function get data from url and process this data and parse to json.
What i need is when the function is called before return the answer store this data into azure table storage.
const axios = require('axios');
const azureStorage = require('azure-storage');
module.exports = async function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.');
const name = (req.query.url || (req.body && req.body.url));
const responseMessage = name
? `Hello you are trying to download file from ${req.body.name} with url ${req.body.url}`
: "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.";
context.res = {
body: {
textParsed: await getData(req.body.url),
statusTable: saveDataOnTable(context),
conectionString: process.env.conectionString
}
};
}
async function getData(url) {
const request = await axios(url).then(response => { return response.data });
const jsonData = await csvJSON(request);
return jsonData;
}
async function csvJSON(csv) {
let regularQuotes = /"/g;
let csvArray = csv.split("\r\n");
let headers = csvArray[0].split(",");
let result = [];
//recorre el array con los datos del csv
for (let index = 1; index < csvArray.length; index ) {
//comprueba que el campo no este vacio
if (!csvArray[index]) continue;
let obj = {};
//guarda la linea actual
let currentline = csvArray[index];
//reemplaza los caracteres de escape como comillas
currentline = regularQuotes[Symbol.replace](currentline, '');
//separa los datos utilizando las comillas como caracter de escape
currentline = currentline.split(",");
for (let j = 0; j < headers.length; j ) {
//elimina espacios de las cabezeras
let head = headers[j].trim();
//elimina espacios de los datos
let value = currentline[j].trim();
//crea el objeto con los valores
obj[head] = value;
}
result.push(obj);
}
//devuelve una string en formato json
return JSON.stringify(result);
}
CodePudding user response:
- There is sdk available to connect and manipulate a table in azure called
@azure/data-tables
. Install it along withuuid
npm install @azure/data-tables
npm install uuid
- Import specific functions from the sdk such as:
const { v4: uuidv4 } = require('uuid');
const { TableClient, AzureNamedKeyCredential } = require("@azure/data-tables");
- Now you will need the connection key of your storage entity. Also please create a table beforehand in that storage space.
const accountname = "";
const accountkey = "";
const tableName = "";
- Now we create a
tableclient
which will connect to the table storage and add the entity to the table.
const credential = new AzureNamedKeyCredential(accountname, accountkey);
const client = new TableClient(`https://${accountname}.table.core.windows.net`, tableName, credential);
- Now we have to create an entity which will be send to the table and then we will send it to table storage.
// I am assuming that the response of the url isin json
let testjsonobject = {};
testjsonobject.language = "javascript";
testjsonobject.platform = "azure functions"
context.log(testjsonobject);
let testjsonobjectString = JSON.stringify(testjsonobject);
let partitionkeynew = uuidv4();;//crypto.randomUUID();
context.log(partitionkeynew);
const entity = {
partitionKey : partitionkeynew,
rowKey:"1",
description:testjsonobjectString
}
let result = await client.createEntity(entity);
complete code :
const { TableServiceClient, odata } = require("@azure/data-tables");
const { v4: uuidv4 } = require('uuid');
const { TableClient, AzureNamedKeyCredential } = require("@azure/data-tables");
module.exports = async function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.');
const accountkey = "";
const accountname = "";
const tableName = "";
const credential = new AzureNamedKeyCredential(accountname, accountkey);
const client = new TableClient(`https://${accountname}.table.core.windows.net`, tableName, credential);
let testjsonobject = {};
testjsonobject.language = "javascript";
testjsonobject.platform = "azure functions"
context.log(testjsonobject);
let testjsonobjectString = JSON.stringify(testjsonobject);
let partitionkeynew = uuidv4();;//crypto.randomUUID();
context.log(partitionkeynew);
const entity = {
partitionKey : partitionkeynew,
rowKey:"1",
description:testjsonobjectString
}
let result = await client.createEntity(entity);
context.log(result);
context.res = {
// status: 200, /* Defaults to 200 */
body: result
};
}
Here result will get a Etag if the operation is successful.