Skip to main content

Node.js Adapter

Note

Since v3.1, @cloudbase/js-sdk has integrated the Node.js adapter by default, requiring no additional installation. If needed, follow the steps below to install and use the adapter.

Overview

The Node.js adapter is designed for the Node.js environment and provides access capability to cloud development services. It allows developers to use feature development in Node.js applications, such as databases, storage, and functions.

Installation

Install the Node.js adapter using npm:

npm i @cloudbase/adapter-node

Quick Start

Usage

const cloudbase = require("@cloudbase/js-sdk");
const adapter = require("@cloudbase/adapter-node");

// Use the Node.js adapter
cloudbase.useAdapters(adapter);

const app = cloudbase.init({
env: "your-env", // Replace this value with your environment id
});

Example

Serverless Cloud Function (SCF) call example

// SCF function call example
const result = await app.callFunction({
name: "your-function-name",
data: {
key: "value",
},
});

Database operation example

// Database operation example
const db = app.database();
// Create Test Set
const testCollection = db.collection("test_collection");
// Insert test data
const insertResult = await testCollection.add({
name: "Node.js test"
timestamp: new Date().toISOString(),
});

File upload example

// Example of Uploading a File
const fileName = `test-files/app-upload-${Date.now()}.jpg`;

const fs = require("fs");
const testFilePath = "/your/local/path/XXX.jpg"; // Replace with your local file path
// Read file content
const fileBuffer = fs.readFileSync(testFilePath);

const uploadResult = await app.uploadFile({
cloudPath: fileName,
filePath: fileBuffer,
onUploadProgress: function (progressEvent) {
console.log("upload progress:", progressEvent);
var percentCompleted = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
);
},
});

Scale Adapter

The Node.js adapter exports the core module, and you can build custom adapters based on it to meet special environment or business requirements.

Adapter Structure Description

The adapter is generated by the genAdapter function, and the returned object contains the following core attributes:

PropertyTypeDescription
reqClassSDKRequestInterfaceHTTP request class, responsible for all network requests (GET/POST/upload/download/streaming)
wsClassWebSocketConstructorWebSocket construct function
sessionStorageStorageInterfaceSession storage implementation
localStorageStorageInterfaceLocal storage implementation
primaryStorageStorageTypeStorage type used by default
rootobjectglobal object reference
getSecretInfofunctionGet Tencent Cloud temporary key information
nodeToolfunctionNode.js tools and methods (auth, template message)
captchaOptionsobjectCaptcha handle callback

Custom Request Class

By inheriting the NodeRequest class, you can expand or override request behavior, such as adding custom request headers, modifying signature logic, intercepting requests/responses.

const { NodeRequest } = require("@cloudbase/adapter-node");

class CustomRequest extends NodeRequest {
// Override getReqOptions to add a custom request header
getReqOptions = async (url, options) => {
const reqOptions = await super.getReqOptions(url, options);
reqOptions.headers = {
...reqOptions.headers,
"X-Custom-Header": "my-value",
};
return reqOptions;
};

// Override fetch to add request/response interception
fetch = async (options) => {
console.log("[request blocking]", options.url);
const result = await super.fetch(options);
console.log("[response interception]", result.statusCode);
return result;
};
}

Custom storage implementation

By default, memory storage is only valid within the process lifecycle. If needed, you can implement your own StorageInterface for persistent storage (such as Redis, file system).

const customStorage = {
mode: "async", // "sync" or "async"
setItem(key, value) {
Write to your storage backend
},
getItem(key) {
Read from your storage backend
},
removeItem(key) {
//Delete from your storage backend
},
clear() {
// Clear storage
},
};

Complete custom adapter example

const cloudbase = require("@cloudbase/js-sdk");
const nodeAdapter = require("@cloudbase/adapter-node");
const { NodeRequest } = nodeAdapter;

// 1. Custom request class
class CustomRequest extends NodeRequest {
getReqOptions = async (url, options) => {
const reqOptions = await super.getReqOptions(url, options);
reqOptions.headers["X-Custom-Header"] = "my-value";
return reqOptions;
};
}

// 2. Custom storage
const redisStorage = {
mode: "async",
async setItem(key, value) {
/* redis.set(key, value) */
},
async getItem(key) {
/* return redis.get(key) */
},
async removeItem(key) {
/* redis.del(key) */
},
async clear() {
/* redis.flushdb() */
},
};

// 3. Assemble custom adapter
const customAdapter = {
genAdapter(options) {
// Get the default adapter
const defaultAdapter = nodeAdapter.default.genAdapter(options);
return {
...defaultAdapter,
// Replace the request class
reqClass: CustomRequest,
// Replace storage implementation
localStorage: redisStorage,
sessionStorage: redisStorage,
};
},
isMatch: nodeAdapter.default.isMatch,
runtime: "custom-node-adapter",
};

// 4. Use a custom adapter
cloudbase.useAdapters(customAdapter);
const app = cloudbase.init({
env: "your-env",
});

Exported utility function

The adapter also exports some utility functions that can be reused in custom adapters:

Export ItemDescription
NodeRequestHTTP request class, inheritable and expandable
parseQueryString(search)Parse query string to an object, support duplicate key autospin to array
createWebStreamFromNodeReadableStream(stream)Convert Node.js ReadableStream to Web ReadableStream

Type export

TypeDescription
ICreateTicketOptsCustom Login Ticket creation options
IGetUserInfoResultUser information query result
IGetEndUserInfoResultEnd user information query result
IUserInfoQueryUser information query request parameter
IContextParamSCF function entry context parameter structure
ICompleteCloudbaseContextSCF function runtime complete environment variable data type
ICredentialsInfoCustom login credentials (RSA private key)