First test :
This result comes from an AJAX call to a Serverless function
Front-end code :
window.addEventListener('DOMContentLoaded', e => {
const resultContainer = document.querySelector('#result-container');
const callServerLessFunction = async () => {
const data = await fetch(`https://hs.antoinebrossault.com/_hcms/api/myfunction?portalid=20783552`)
if (!data.ok) {
const errorText = await data.text();
throw new Error(errorText);
}
const json = await data.json();
resultContainer.insertAdjacentHTML('afterbegin',JSON.stringify(json));
};
document.querySelector('#run-one').addEventListener('click', callServerLessFunction);
});
Cloud function code
You have to create a new function in the design manager, by clicking on "File" then "new file"
Here is the code for myFunction.js
// Require axios library, to make API requests.
// Should be available on
// https://hs.antoinebrossault.com/_hcms/api/myfunction?portalid=20783552
// https://{domainName}/_hcms/api/{endpoint-name/path}?portalid={hubId}.
const axios = require('axios');
// Environment variables from your serverless.json
// process.env.globalConfigKey
exports.main = (context, sendResponse) => {
// your code called when the function is executed
// context.params
// context.body
// context.accountId
// context.limits
// secrets created using the CLI are available in the environment variables.
// process.env.secretName
//sendResponse is what you will send back to services hitting your serverless function.
sendResponse({body: {message:"my response"}, statusCode: 200});
};
Env and routing
{
"runtime": "nodejs12.x",
"version": "1.0",
"environment": {},
"endpoints": {
"myFunction": {
"method": "GET",
"file": "myFunction.js"
}
}
}
To edit the code locally run :
First import the code from the design manager
hs fetch serverless.functions
Upload a function :
hs upload --account=antoine serverless.functions/myFunction.js serverless.functions/myFunction.js
When the function is uploaded no need to go in the design manager to re-deploy it, it's done automaticly
To find the name of the account ( here : "antoine" ) refer to the hubspot.config.yml file
Logging
Log execution of a given function :
hs logs myFunction --follow