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
User
what metadata will I receive from sharepoint?
Assistant
The metadata you receive from SharePoint in a webhook notification is limited. The webhook payload contains the following properties:
subscriptionId: The unique identifier of the webhook subscription.
clientState: The client state value that you provided when you created the subscription. This is useful for verifying the authenticity of the webhook payload.
expirationDateTime: The expiration date and time of the webhook subscription.
User
what's the full list of metadata I will get?
Assistant
The full list of metadata properties you can get from a SharePoint file depends on the specific file and the SharePoint setup. However, some common metadata properties include:
Author: The user who created the file.
Editor: The user who last modified the file.
Created: The date and time the file was created.
Modified: The date and time the file was last modified.
FileRef: The server-relative URL of the file.
FileLeafRef: The file name including the extension.
User
can you change the webhook code to pipe the file content direct from sharepoint to blob storage without reading it all into memory in the function
Assistant
To pipe the file content directly from SharePoint to Azure Blob Storage without reading it all into memory in the function, you can use the stream package and the node-fetch package. First, you'll need to install these packages:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
To create an Azure Function that receives a webhook notification from SharePoint, copies the new file into an Azure Blob container, and applies a retention policy based on the file metadata, follow these steps:
func new --template "HTTP trigger" --name CopyFileToBlob
Edit the CopyFileToBlob/index.js file with the following code:
javascript
const { BlobServiceClient, StorageSharedKeyCredential } = require('@azure/storage-blob');
// Replace with your storage account name and account key
const accountName = 'your_storage_account_name';
const accountKey = 'your_storage_account_key';
const sharedKeyCredential = new StorageSharedKeyCredential(accountName, accountKey);
const blobServiceClient = new BlobServiceClient(`https://${accountName}.blob.core.windows.net`, sharedKeyCredential);
module.exports = async function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.');
if (req.body && req.body.value && req.body.value.length > 0) {
const notification = req.body.value[0];
const fileUrl = notification.resource;
const fileName = fileUrl.split('/').pop();
const response = await fetch(fileUrl, {
headers: {
'Authorization': `Bearer ${process.env.SPN_ACCESS_TOKEN}`
}
});
const fileData = await response.arrayBuffer();
// Replace with your container name
const containerName = 'your-container-name';
const containerClient = blobServiceClient.getContainerClient(containerName);
const blockBlobClient = containerClient.getBlockBlobClient(fileName);
const uploadResponse = await blockBlobClient.uploadData(fileData, {
blobHTTPHeaders: {
blobContentType: notification.file.contentType
},
metadata: {
// Add custom metadata based on SharePoint file metadata
}
});
context.log(`File uploaded to Blob storage with status: ${uploadResponse._response.status}`);
// Apply retention policy based on file metadata
// ...
context.res = {
status: 202,
body: 'File processed successfully'
};
} else {
context.res = {
status: 400,
body: 'Invalid request format'
};
}
};
Replace the placeholders your_storage_account_name, your_storage_account_key, and your-container-name with the appropriate values for your Azure Blob Storage account.
Apply the retention policy based on the file metadata (in the commented section) as needed.
Deploy the Azure Function to your Azure subscription.
Now, you need to register the webhook in SharePoint to receive notifications when a new file is created. To do that, follow the Microsoft documentation on creating and deleting SharePoint webhooks using REST. Point the notificationUrl to the deployed Azure Function's URL.
Please note that you might need to handle authentication and authorization for SharePoint, which is not covered in this example. For more information, refer to the Microsoft documentation on SharePoint authentication.
resource: The URL of the resource that triggered the notification, e.g., the list item or file that was created or modified.
resourceId: The unique identifier of the resource that triggered the webhook notification.
tenantId: The unique identifier of the tenant where the subscription was registered.
siteUrl: The URL of the site collection where the subscription was registered.
webId: The unique identifier of the web (site) where the subscription was registered.
Please note that the webhook payload does not include detailed file metadata like author, creation date, content type, etc. To get this information, you need to make an additional API call to SharePoint using the resource URL.
Here's an example of how to get additional file metadata using the SharePoint REST API:
javascript
async function getFileMetadata(fileUrl) {
const apiUrl = `${fileUrl}/ListItemAllFields`;
const response = await fetch(apiUrl, {
headers: {
'Authorization': `Bearer ${process.env.SPN_ACCESS_TOKEN}`,
'Accept': 'application/json;odata=verbose'
}
});
if (!response.ok) {
throw new Error(`Failed to fetch file metadata: ${response.statusText}`);
}
const data = await response.json();
return data.d;
}
You can call this function within the Azure Function after receiving the webhook notification:
The fileMetadata object will contain the additional metadata for the file, including properties like Author, Editor, Created, Modified, and more. You can use this information to apply a retention policy or for any other purpose.
UniqueId: The unique identifier of the file.
File_x0020_Type: The file extension.
ContentTypeId: The content type identifier of the file.
Title: The title of the file.
File_x0020_Size: The file size in bytes.
In addition to these properties, SharePoint allows you to create custom columns to store additional metadata for files. The available properties will depend on the specific columns configured in your SharePoint site.
To get a list of all available metadata properties for a specific file, you can use the SharePoint REST API. Here's an example of how to get all available metadata properties for a given file URL:
javascript
async function getAllFileMetadata(fileUrl) {
const apiUrl = `${fileUrl}/ListItemAllFields`;
const response = await fetch(apiUrl, {
headers: {
'Authorization': `Bearer ${process.env.SPN_ACCESS_TOKEN}`,
'Accept': 'application/json;odata=verbose'
}
});
if (!response.ok) {
throw new Error(`Failed to fetch file metadata: ${response.statusText}`);
}
const data = await response.json();
return data.d;
}
You can call this function within the Azure Function after receiving the webhook notification:
The allFileMetadata object will contain all the available metadata properties for the file. Keep in mind that the actual properties might vary depending on your SharePoint setup and the specific file.
bash
npm install --save stream node-fetch
Next, modify the CopyFileToBlob/index.js file with the following code:
With this modification, the file content is streamed directly from SharePoint to Azure Blob Storage without being fully loaded into the function's memory. The PassThrough stream is used to pipe the file content from the node-fetch response to the Blob Storage upload stream.