admin管理员组

文章数量:1405389

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?

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?

Share Improve this question edited Oct 15, 2020 at 7:46 Yaniv Irony asked Oct 15, 2020 at 7:35 Yaniv IronyYaniv Irony 1591 silver badge5 bronze badges 2
  • javascript don't support imperative binding pattern, so we can not use IBinder. We need to get value from the param of request or from the body of the request. Any other doubts? – suziki Commented Oct 15, 2020 at 9:33
  • 1 I need to get the out blob name in the function. Or get rand-guid at least in the function. Is that possible? i tried this: var randGuid = context.bindingData.sys.randGuid but its not the same guid from the binding – Yaniv Irony Commented Oct 15, 2020 at 10:57
Add a ment  | 

3 Answers 3

Reset to default 3

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 puted 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.

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

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

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

本文标签: javascriptUse variables in Azure Functions out bindingStack Overflow