Skip to content

custom API

Custom APIs

Basic code

  • Custom API has the async 'main' function. In which users will write their custom logic.
1
2
3
return {
    hello: 'world'
};

await

  • Write 'await' before the global object 'g' to write asynchronous code.
  • Without 'await' it can be created problems.
1
2
3
4
5
return await g.sys.db.getAll({
    instance: "INSTANCE_NAME",
    collection: "COLLECTION_NAME",
    database: "DATABASE_NAME",
});

true

  • Write 'true' that will help to non-stop execution of the custom API if that API gets an error response.
  • If the user does not write the 'true' it will stop the execution and throw the error.
  • One more use of 'true' is it will return whole response not only response data.
let saveData = await g.sys.db.saveSingleOrMultiple({
    instance: "INSTANCE_NAME",
    collection: "COLLECTION_NAME",
    database: "DATABASE_NAME",
    saveData: {},
    headers: {}
}, true);
let countOfAllData = await g.sys.db.count({
    instance: "INSTANCE_NAME",
    collection: "COLLECTION_NAME",
    database: "DATABASE_NAME",
}, true);
return { saveData, countOfAllData };

Throw error

  • In custom API user can throw an error using the 'throw' keyword.
1
2
3
4
5
6
7
8
9
let saveData = await g.sys.db.saveSingleOrMultiple({
    instance: "INSTANCE_NAME",
    collection: "COLLECTION_NAME",
    database: "DATABASE_NAME",
    saveData: {},
    headers: {}
}, true);
if (saveData.success === false) throw 'Your data is not saved!';
else return saveData;

Get file

  • You can create a custom API that will download files for the application user.
g.res.contentType = 'image/gif';
return `data:image/gif;base64,R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOwA=`

Download file

import * as T from 'types';
import * as fs from 'fs';
import * as path from 'path';
async function main(g: T.IAMGlobal) {
    // always write file in uploads directlry which you want to send to user.
    // you can write other files in any directory which you don't want to send to user.
    let filePath = path.join(__dirname, 'uploads', 'myfile.txt');
    await fs.promises.writeFile(filePath, 'file 1 content', { encoding: 'utf8' });
    return {
        // just provide file name which is written to "uploads" directory
        __am__downloadFilePath: 'myfile.txt',
        __am__downloadFolderFileName: 'newName.txt', // download file will have this name.
    }
};
module.exports = main;
import * as T from 'types';
import * as fs from 'fs';
import * as path from 'path';
async function main(g: T.IAMGlobal) {
    return {
        __am__downloadFileOrFolderPaths: [
            {
                fsSource: path.join('folder1', 'folder2', 'folder3', 'data_folder'), // path into uploads folder
                archiveDestination: 'data_folder', // path in zip file, so data_folder folder will be directly available in zip file.
            },
        ],
        __am__downloadFolderFileName: `output.zip`, // download file will have this name.
    }
};
module.exports = main;

Download files & folders

import * as T from 'types';
import * as fs from 'fs';
import * as path from 'path';
async function main(g: T.IAMGlobal) {
    // always write file in uploads directlry which you want to send to user.
    // you can write other files in any directory which you don't want to send to user.
    let filePath = path.join(__dirname, 'uploads', 'myfile.txt');
    await fs.promises.writeFile(filePath, 'file 1 content', { encoding: 'utf8' });
    return {
        // You can provide list of files or folders, it will will make zip and send to user.
        __am__downloadFileOrFolderPaths: [
            'myfile.txt', // file name
            'someFolder', // folder name
        ],
        __am__downloadFolderFileName: 'zipFile.zip', // this will be zip file name
    }
};
module.exports = main;

Download file from Angular sent by custom API

async function downloadFileFromBrowser() {
    const requestPayload = {};
    const requestHeaders = {};
    const resp = <any>await this.http.post(`API Maker custom API endpoint`, requestPayload, {
        headers: requestHeaders,
        responseType: <any>'text',
        observe: 'response',
    }).toPromise();
    const fileName = resp.headers.get('content-filename');
    await this.downloadFileFromBlob('application/zip', resp.body, fileName);
    return resp;
}

async function downloadFileFromBlob(contentType, base64Data: any, fileName) {
    const a = document.createElement('a');
    document.body.appendChild(a);
    a.style.display = 'none';

    let blob;
    if (base64Data instanceof Blob) {
        blob = base64Data;
    } else {
        const base64Response = await fetch(`data:${contentType};base64,` + base64Data);
        blob = await base64Response.blob();
    }

    const url = window.URL.createObjectURL(blob);
    a.href = url;
    a.download = fileName;
    a.click();
    window.URL.revokeObjectURL(url);
}