give me the code in nodejs for an azure function that receives a webook notification from Sharepoint where a new file is created there, receives metadata about the new file and then copies that new file into an Azure blob container, applying a retention policy based on the file metadata
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Here is a Node.js code example for an Azure Function that achieves the described workflow:
Prerequisites:
Azure Function setup:
Create a new Azure Function App (Node.js runtime).
Create a new Azure Function within the app (e.g., HttpTrigger or EventGridTrigger depending on how SharePoint sends the webhook notification; for this example, we'll assume HttpTrigger).
Azure Storage setup:
Create an Azure Storage account.
Create a Blob container within the storage account (e.g., myblobcontainer).
SharePoint Webhook setup:
Configure a webhook in SharePoint to send notifications to your Azure Function's HTTP endpoint when a new file is created. The payload should include the file metadata.
To set up the webhook, you will need to register an Azure AD application, grant the necessary permissions, and configure the webhook endpoint in SharePoint. You can find detailed instructions in the official Microsoft documentation: https://learn.microsoft.com/en-us/sharepoint/dev/apis/webhooks
Azure Function App settings:
Store the following as application settings in your Azure Function App:
AZURE_STORAGE_ACCOUNT: Your Azure Storage account name.
AZURE_STORAGE_ACCESS_KEY: Your Azure Storage account key.
AZURE_STORAGE_CONTAINER_NAME: The name of your Blob container (e.g., myblobcontainer).
SHAREPOINT_SITE_URL: The URL of your SharePoint site (for constructing file download URLs).
SHAREPOINT_CLIENT_ID and SHAREPOINT_CLIENT_SECRET: If using client credentials flow for authentication with SharePoint (optional, depending on your auth setup).
Azure Function Code (index.js):
javascript
const axios = require('axios');
const { BlobServiceClient } = require('@azure/storage-blob');
const { DefaultAzureCredential } = require('@azure/identity');
module.exports = async function (context, req) {
context.log('SharePoint Webhook Notification Received');
// **Step 1: Parse SharePoint Webhook Notification**
const fileMetadata = req.body;
const {
FileLeafRef: { UniqueId: fileId },
File: { Name: fileName },
// Add other metadata properties as needed (e.g., author, creation date)
Author: { LookupValue: fileAuthor },
TimeCreated,
} = fileMetadata;
// **Step 2: Authenticate with SharePoint (if using client credentials flow)**
// NOTE: Omit this section if your webhook notification includes a valid bearer token or if you're handling auth differently
const sharepointAuth = async () => {
const client = new DefaultAzureCredential();
const token = await client.getToken(`https://${SHAREPOINT_SITE_URL}/.default`);
return token.token;
};
// **Step 3: Download the new file from SharePoint**
const downloadFile = async (sharepointToken) => {
const fileUrl = `https://${SHAREPOINT_SITE_URL}/_api/web/GetFileByServerRelativeUrl('/${fileId}')/$value`;
const headers = sharepointToken
? { Authorization: `Bearer ${sharepointToken}` }
: {}; // Adjust headers based on your auth setup
try {
const response = await axios.get(fileUrl, { headers, responseType: 'arraybuffer' });
if (response.status === 200) {
return response.data;
} else {
throw new Error(`Failed to download file: ${response.statusText}`);
}
} catch (error) {
context.log.error('Error downloading file from SharePoint:', error);
throw error;
}
};
// **Step 4: Upload the file to Azure Blob Storage**
const uploadFileToBlobStorage = async (fileBuffer) => {
const blobServiceClient = new BlobServiceClient(
`https://${process.env.AZURE_STORAGE_ACCOUNT}.blob.core.windows.net`,
new DefaultAzureCredential()
);
const containerClient = blobServiceClient.getContainerClient(process.env.AZURE_STORAGE_CONTAINER_NAME);
const blockBlobClient = containerClient.getBlockBlobClient(fileName);
const uploadOptions = {
blobHTTPHeaders: {
// Apply metadata to the blob (optional)
blobContentType: 'application/octet-stream',
blobContentDisposition: `attachment; filename="${fileName}"`,
},
};
// **Apply Retention Policy based on file metadata**
// Example: Retain files created by a specific author for 1 year, otherwise retain for 6 months
const retentionDays =
fileAuthor === 'SpecificAuthor' ? 365 : 183; // Adjust logic based on your retention policy needs
uploadOptions.tags = `RetentionDays=${retentionDays}`;
try {
await blockBlobClient.uploadData(fileBuffer, uploadOptions);
} catch (error) {
context.log.error('Error uploading file to Azure Blob Storage:', error);
throw error;
}
};
try {
// **Optional:** Authenticate with SharePoint
const sharepointToken = (await sharepointAuth()) || null;
// Download file from SharePoint
const fileBuffer = await downloadFile(sharepointToken);
// Upload file to Azure Blob Storage
await uploadFileToBlobStorage(fileBuffer);
context.res = { body: `File ${fileName} successfully copied to Azure Blob Storage` };
} catch (error) {
context.log.error('Error processing SharePoint webhook notification:', error);
context.res = { status: 500, body: 'Error processing file' };
}
};
Important Notes:
Authentication: This example assumes either client credentials flow for SharePoint authentication or that the webhook notification includes a valid bearer token. Adjust the authentication logic based on your setup.
Retention Policy: The example applies a simple retention policy based on the file author. Modify the logic in uploadFileToBlobStorage to fit your specific retention policy requirements.
Error Handling: Basic error handling is included. Enhance this as needed for production environments.
Dependencies: Ensure you have @azure/storage-blob, @azure/identity, and axios installed in your Azure Function App by running npm install with the appropriate package names in your package.json.
Testing: Thoroughly test this function with various file metadata scenarios to ensure it works as expected in your environment.
Authentication with SharePoint:
To authenticate with SharePoint, you can use the client credentials flow, which involves registering an Azure AD application and granting the necessary permissions. Here’s a high-level overview of the process: