Create custom API functions
EXAMPLE - Creating your custom API is needed if you want to make interactive functions in your sites.
API functions are not cached (by default) and are also allowed to access query string and form parameters. With API functions you can also write / store data to your Docly site / database. Normal pages (.hash files) can't read from the query string and can only produce a single static output as it is cached (by design) in the system.
Create your API handler
Place your API functions in the #/API folder where it is only possible to create .hash files that returns JSON or JS files that return objects (converted automatically to JSON). The following example returns the date formatted:
#/API/Test.js
export default () => {
let result = { "date" : docly.format(new Date(), "yyyyMMdd") };
return result;
}; Endpoint for this function is: https://yoursite/API/Test
⚠️ Your API is addressed under the "/API/" prefix.
Use your API handler
Call your API functions from the browser with fetch and handle the results:
<html>
<head>
<title>Test page</title>
</head>
<body>
The date is: <span id="Date">Loading ...</span>
<script>
fetch("~/API/Test")
.then(response => response.json())
.then(data => {
document.getElementById("Date").textContent = data.date;
})
.catch(err => {
document.getElementById("Date").textContent = "Could not load the date";
});
</script>
</body>
</html> Use tilde ~ to address the root folder of your site.
Get parameters from query string (GET and POST methods)
For API functions you can use dynamic values such as query string params. The result of the API call will also never be cached.
Query string parameters are bound to the parameters of your function by name. You can also read them with: let value = query.paramname;
Note that the param names are case sensitive!
// #/API/MyFunction.js — GET ~/API/MyFunction?folder=Products
export default (folder) => {
// Only list folders you intend to expose — folder comes from the caller
if (folder !== "Products" && folder !== "Services") throw new Error("Unknown folder");
return docly.getFolders(folder);
}; Calling the API with fetch (GET):
fetch("~/API/MyFunction?folder=" + encodeURIComponent("Products")).then(function(response) {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(function(data) {
// TODO: handle the data
})
.catch(function(error) {
console.error("Error: " + error.message);
}); Get parameters from form (POST method)
For API functions where you use post method you can read from the form values.
Fields in the posted body — form fields or a JSON object — are bound to the parameters of your function by name. You can also read them with: let value = form.paramname; Note that a form-encoded field arrives as a list of strings, not a string — compare with String(value), and docly.isString(value) is false for it.
Note that the param names are case sensitive! The body is already decoded, so do not call JSON.parse on it.
// #/API/MyFunction.js — POST { "folder": "Products" }
export default (folder) => {
if (request.method != "POST") throw new Error("Verb not supported");
if (folder !== "Products" && folder !== "Services") throw new Error("Unknown folder");
return docly.getFolders(folder);
}; Example url: https://yoursite/API/MyFunction
Calling the API with fetch (POST):
fetch('~/API/MyFunction', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ folder: "Products" })
})
.then(function(response) {
if (!response.ok) {
return response.json().then(function(err) {
throw new Error(err.message || err.Message || 'Unknown error occurred');
});
}
return response.json();
})
.then(function(data) {
console.log("Submit response", data);
// TODO ...
})
.catch(function(ex) {
// TODO ...
// Error occurred in code
}); Data functions
API code can modify Docly-data with the following API only functions:
Function | Description |
|---|---|
docly.saveFile(filepath, json, [schemaPath]) | Create or update a Docly document. |
docly.patchFile(filepath, jsonPatch) | Updates a Docly document by overwriting only specified keys in JSON. |
docly.deleteFile(filepath) | Delete a Docly document. |
docly.moveFile(filepath, folderpath) | Move a Docly document. |
Note that these functions are not available outside your API code folder (#/API). Extra charges will apply when using the API features.
Function that returns an array
Filename: #/API/GetRoomAvail.js
export default () => {
let today = docly.format(new Date(), "yyyy-MM-dd");
let liste = docly.getFiles("Tenancies", "*", 1);
let result = [];
for(let item of liste) {
if (item.To > today) {
let obj = {
"Roomno" : item.Roomno,
"From" : item.From,
"To" : item.To
};
result.push(obj);
}
}
return result;
}; Validate incoming parameters
To validate parameters in a function handler you can use these utility functions. They return true or false — throw an error yourself when a value is invalid:
Function | Description |
|---|---|
docly.isString(value, [length]) | true if the parameter is a non-empty string, otherwise false. |
docly.isNum(value, [min], [max]) | true if the parameter is a number, otherwise false. |
docly.isEmail(value) | true if the parameter is a valid email address, otherwise false. |
docly.isName(value) | If parameter is a string and contains at least two words separated with space. |
GET method example:
export default (name, email, age, address) => {
// Validate params with if statements and throw new Error
if (!docly.isString(name, 5)) throw new Error("Name is required!");
if (!docly.isEmail(email)) throw new Error("Email is required!");
if (!docly.isNum(age)) throw new Error("Age is required!");
if (!docly.isNum(age, 18, 100)) throw new Error("Age must be between 18 and 100!");
if (!address) throw new Error("Address is not specified!");
// ....
};