Yaniv Irony
Yaniv Irony

Reputation: 159

Use variables in Azure Functions out binding

I'm using Azure functions with javascript, and i would like to modify the out binding of path in my functions. For example this is my function.json:

{
  "bindings": [
    {
      "authLevel": "function",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    },
    {
      "name": "outputBlob",
      "path": "container/{variableCreatedInFunction}-{rand-guid}",
      "connection": "storagename_STORAGE",
      "direction": "out",
      "type": "blob"
    }
  ]

I Would like to set {variableCreatedInFunction} in index.js, for example:

module.exports = async function (context, req) {
    const data = req.body
    const date = new Date().toISOString().slice(0, 10)
    const variableCreatedInFunction = `dir/path/${date}`
    if (data) {
        var responseMessage = `Good`
        var statusCode = 200
        context.bindings.outputBlob = data
    } else {
        var responseMessage = `Bad`
        var statusCode = 500
    }
    context.res = {
        status: statusCode,
        body: responseMessage
    };
}
 

Couldn't find any way to this, is it possible?

Upvotes: 10

Views: 2820

Answers (3)

ChrisT
ChrisT

Reputation: 1

I've been trying to look for a solution for like a week and found one. This cannot be done dynamically, so you should make a programmatic solution. Delete the configuration in function.json and make the connection in your implementation. You should install the azure/storage-blob package and use BlobServiceClient function.

const { BlobServiceClient } = require('@azure/storage-blob');


const blobServiceClient = BlobServiceClient.fromConnectionString(process.env.AzureWebJobsStorage);

const uploadContentToBlob = async (containerName, blobName, content) => {
    const containerClient = blobServiceClient.getContainerClient(containerName);
    const blockBlobClient = containerClient.getBlockBlobClient(blobName);
    await blockBlobClient.upload(content, Buffer.byteLength(content));
};

try {
  await uploadContentToBlob('<blobName>', `${logFileName}.txt`, <blobContent>);
  context.log('All blobs have been uploaded successfully.');
} catch (error) {
    context.log(`Error uploading blobs: ${error.message}`);
}

Upvotes: 0

Kristin
Kristin

Reputation: 1391

Bindings are resolved before the function executes. You can use {DateTime} as a binding expression. It will by default be yyyy-MM-ddTHH-mm-ssZ. You can use {DateTime:yyyy} as well (and other formatting patterns, as needed).

Imperative bindings (which is what you want to achieve) is only available in C# and other .NET languages, the docs says:

Binding at runtime In C# and other .NET languages, you can use an imperative binding pattern, as opposed to the declarative bindings in function.json and attributes. Imperative binding is useful when binding parameters need to be computed at runtime rather than design time. To learn more, see the C# developer reference or the C# script developer reference.

MS might've added it to JS as well by now, since I'm pretty sure I read that exact section more than a year ago, but I can't find anything related to it. Maybe you can do some digging yourself.

If your request content is JSON, the alternative is to include the path in the request, e.g.:

{
  "mypath":"a-path",
  "data":"yourdata"
}

You'd then be able to do declarative binding like this:

{
  "name": "outputBlob",
  "path": "container/{mypath}-{rand-guid}",
  "connection": "storagename_STORAGE",
  "direction": "out",
  "type": "blob"
}

In case you need the name/path to your Blob, you'd probably have to chain two functions together, where one acts as the entry point and path generator, while the other is handling the Blob (and of course the binding). It would go something like this:

  • Declare 1st function with HttpTrigger and Queue (output).
  • Have the 1st function create your "random" path containing {date}-{guid}.
  • Insert a message into the Queue output with the content {"mypath":"2020-10-15-3f3ecf20-1177-4da9-8802-c7ad9ada9a33", "data":"some-data"} (replacing the date and guid with your own generated values, of course...)
  • Declare 2nd function with QueueTrigger and your Blob-needs, still binding the Blob path as before, but without {rand-guid}, just {mypath}.
  • The mypath is now used both for the blob output (declarative) and you have the information available from the queue message.

Upvotes: 3

suziki
suziki

Reputation: 14080

It is not possiable to set dynamic variable in .js and let the binding know.

The value need to be given in advance, but this way may achieve your requirement:

index.js

module.exports = async function (context, req) {
    context.bindings.outputBlob = "This is a test.";
    context.done();
    context.res = {
        body: 'Success.'
    };
}

function.json

{
  "bindings": [
    {
      "authLevel": "anonymous",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    },
    {
      "name": "outputBlob",
      "path": "test/{test}",
      "connection": "str",
      "direction": "out",
      "type": "blob"
    }
  ]
}

local.settings.json

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "",
    "FUNCTIONS_WORKER_RUNTIME": "node",
    "str":"DefaultEndpointsProtocol=https;AccountName=0730bowmanwindow;AccountKey=xxxxxx;EndpointSuffix=core.windows.net"
  }
}

Or you can just put the output logic in the body of function. Just use the javascript sdk.

Upvotes: 1

Related Questions