### async/await example (node >= 7.6) Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/README.md Example using async/await to create a service, create a function, invoke it, and update it. Shows using rawBuf option to get buffer response. ```javascript 'use strict'; const FCClient = require('@alicloud/fc2'); var client = new FCClient('', { accessKeyID: '', accessKeySecret: '', region: 'cn-shanghai', }); var serviceName = ''; var funcName = ''; async function test () { try { var resp = await client.createService(serviceName); console.log('create service: %j', resp); resp = await client.createFunction(serviceName, { functionName: funcName, handler: 'counter.handler', memorySize: 128, runtime: 'nodejs4.4', initializer: 'counter.initializer', code: { zipFile: fs.readFileSync('/tmp/counter.zip', 'base64'), }, }); console.log('create function: %j', resp); // by default , resp is decoded by utf8 resp = await client.invokeFunction(serviceName, funcName, null); console.log('invoke function: %j', resp); // respWithBuf is returned as buffer if isRawBuf is set to be true in opts respWithBuf = await client.invokeFunction(serviceName, funcName, null, {}, 'LATEST', {rawBuf:true}); uResp = await client.updateFunction(serviceName, funcName, { description: 'updated function desc', initializationTimeout: 60, }); console.log('update function: %j', resp); } catch (err) { console.error(err); } } test().then(); ``` -------------------------------- ### Promise example Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/README.md Example using Promise to create a service, create a function, and invoke it. Requires '@alicloud/fc2' and uses fs.readFileSync for zipFile. ```javascript 'use strict'; var FCClient = require('@alicloud/fc2'); var client = new FCClient('', { accessKeyID: '', accessKeySecret: '', region: 'cn-shanghai', timeout: 10000 // Request timeout in milliseconds, default is 10s }); var serviceName = ''; var funcName = ''; client.createService(serviceName).then(function(resp) { console.log('create service: %j', resp); return client.createFunction(serviceName, { functionName: funcName, handler: 'index.handler', memorySize: 128, runtime: 'nodejs4.4', code: { zipFile: fs.readFileSync('/tmp/index.zip', 'base64'), }, }); }).then(function(resp) { console.log('create function: %j', resp); return client.invokeFunction(serviceName, funcName, 'event'); }).then(function(resp) { console.log('invoke function: %j', resp); }).catch(function(err) { console.error(err); }); ``` -------------------------------- ### Install fc2 Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/README.md Install the official fc2 release version via npm. ```bash npm install @alicloud/fc2 --save ``` -------------------------------- ### createService example Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-services.md Example usage of createService with a description, role, and logConfig. Logs the returned serviceId. ```javascript const resp = await client.createService('my-service', { description: 'Demo service', role: 'acs:ram::123:role/fc-role', logConfig: { project: 'fc-log', logstore: 'fc-logstore' } }); console.log(resp.data.serviceId); ``` -------------------------------- ### createCustomDomain example Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-triggers.md Example call to create a custom domain with protocol and route configuration. ```javascript const resp = await client.createCustomDomain('api.example.com', { protocol: 'HTTP', routeConfig: { routes: [{ path: '/api/*', serviceName: 'my-service', functionName: 'handler' }] } }); ``` -------------------------------- ### createFunction example (default) Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-functions.md Example of creating a function with inline zipFile code. Uses default path without withoutCodeLimit. ```javascript const resp = await client.createFunction('my-service', { functionName: 'handler', handler: 'index.handler', memorySize: 128, runtime: 'nodejs12', code: { zipFile: fs.readFileSync('/tmp/index.zip', 'base64') } }); ``` -------------------------------- ### listFunctionAsyncConfigs usage example Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-scaling.md Example call to list async invoke configurations for a function named 'handler' in service 'my-service'. ```javascript const resp = await client.listFunctionAsyncConfigs('my-service', 'handler'); ``` -------------------------------- ### Install old version fc Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/README.md Install the old version of fc (1.x branch) via npm. ```bash npm install @alicloud/fc --save ``` -------------------------------- ### get(path, query, headers) Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client.md Convenience method for making a GET request. It calls `request` with the GET method and returns the promise. ```APIDOC ## get(path, query, headers) ### Description Convenience method for making a GET request. It calls `request` with the GET method and returns the promise. ### Method GET ### Endpoint `${endpoint}/${version}${path}[?query]` ### Parameters #### Path Parameters - `path` (string) - Required - Request path #### Query Parameters - `query` (object | null) - Optional - Query-string parameters #### Headers - `headers` (object) - Optional - Custom headers ### Response Returns the [request](#requestmethod-path-query-body-headers-opts) promise. ``` -------------------------------- ### getCustomDomain usage example Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-triggers.md Example call to fetch custom domain information for 'api.example.com'. ```javascript const resp = await client.getCustomDomain('api.example.com'); ``` -------------------------------- ### Example low-level calls Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client.md Shows low-level usage of client.get and client.post with query parameters and body. ```javascript const resp = await client.get('/services', { limit: 10 }); const created = await client.post('/services', { serviceName: 'demo' }); ``` -------------------------------- ### getProvisionConfig usage example Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-scaling.md Example call to getProvisionConfig with service name 'my-service', function name 'handler', and qualifier 'v1'. Logs the target and current provision values from the response data. ```javascript const resp = await client.getProvisionConfig('my-service', 'handler', 'v1'); console.log(resp.data.target, resp.data.current); ``` -------------------------------- ### get(path, query, headers) method Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client.md Convenience method that calls request with HTTP GET. Accepts path, query parameters, and custom headers. ```javascript get(path, query, headers) { return this.request('GET', path, query, null, headers); } ``` -------------------------------- ### listCustomDomains example Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-triggers.md Example call to list custom domains with a prefix filter. ```javascript const resp = await client.listCustomDomains({ prefix: 'api.' }); ``` -------------------------------- ### putProvisionConfig usage example Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-scaling.md Example call to putProvisionConfig with service name 'my-service', function name 'handler', qualifier 'v1', and options `{ target: 10 }` to set the provision target. ```javascript const resp = await client.putProvisionConfig('my-service', 'handler', 'v1', { target: 10 }); ``` -------------------------------- ### listVersions usage example Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-services.md Calls listVersions with a service name and options specifying direction FORWARD. ```javascript const resp = await client.listVersions('my-service', { direction: 'FORWARD' }); ``` -------------------------------- ### Using getTempBucketToken() Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-functions.md Example of calling getTempBucketToken() and logging the returned ossRegion and ossBucket from the data property. ```javascript const { data } = await client.getTempBucketToken(); console.log(data.ossRegion, data.ossBucket); ``` -------------------------------- ### get(path, query, headers) Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client.md Performs an HTTP GET request to the Function Compute API. ```APIDOC ## Method: get(path, query, headers) ### Description Performs an HTTP GET request to the Function Compute API. ### Parameters - **path** (string) - Required - Request path. - **query** (object) - Optional - Query parameters. - **headers** (object) - Optional - Additional headers. ### Returns - **Promise** - Resolves with a normalized response object `{ headers, data }`. ``` -------------------------------- ### get(path, query, headers) Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/index.md Performs a GET request to the specified path. This is a convenience wrapper around the request method. ```APIDOC ## get(path, query, headers) ### Description Performs a GET request to the specified path. This is a convenience wrapper around the request method. ### Method GET ### Endpoint client.get(path, query, headers) ### Parameters - **path** (string) - Required - API path - **query** (object) - Optional - Query parameters - **headers** (object) - Optional - Request headers ### Request Example ```javascript const response = await client.get('/services', {}, {}); ``` ### Response Returns a Promise that resolves to the API response. ``` -------------------------------- ### getService: GET /services/ Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-services.md GETs a single service by name, optionally including a version/alias qualifier in the path as serviceName.qualifier. Returns a Promise of { headers, data } where data is the service information object. ```javascript getService(serviceName, headers = {}, qualifier) { return this.get( `/services/${getServiceName(serviceName, qualifier)}`, null, headers ); } ``` ```javascript const resp = await client.getService('my-service', {}, 'v1'); // GET /services/my-service.v1 ``` -------------------------------- ### createFunction example (large code via temp OSS bucket) Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-functions.md Example of creating a function with large code using withoutCodeLimit: true. Code is uploaded to a temporary OSS bucket; zipFile is a file path. ```javascript const resp = await client.createFunction('my-service', { functionName: 'big-fn', handler: 'index.handler', memorySize: 512, runtime: 'nodejs12', instanceType: 'e1', withoutCodeLimit: true, code: { zipFile: '/tmp/big.zip' } // file path; uploadCodeToTmpOssBucket stats it }); ``` -------------------------------- ### listLayerVersions usage example Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-tags-layers-account.md Calls listLayerVersions with a layer name to fetch its versions. The response data is not used in this example. ```javascript const resp = await client.listLayerVersions('my-layer'); ``` -------------------------------- ### publishLayerVersion usage example Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-tags-layers-account.md Example call to publishLayerVersion with a layer name, description, and base64-encoded zip file. The `code` option uses `zipFile` to provide the layer content. ```javascript const resp = await client.publishLayerVersion('my-layer', { description: 'shared utils', code: { zipFile: fs.readFileSync('/tmp/layer.zip', 'base64') } }); ``` -------------------------------- ### getFunctionAsyncConfig usage example Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-scaling.md Example call to `getFunctionAsyncConfig` with a service name, function name, and qualifier 'LATEST'. The response is awaited and stored in `resp`. ```javascript const resp = await client.getFunctionAsyncConfig('my-service', 'handler', 'LATEST'); ``` -------------------------------- ### publishVersion usage example Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-services.md Calls publishVersion with a service name and description, then logs the versionId from the response data. ```javascript const resp = await client.publishVersion('my-service', 'release 1.0'); console.log(resp.data.versionId); ``` -------------------------------- ### getLayerVersion usage example Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-tags-layers-account.md Example call to getLayerVersion, retrieving version 3 of the layer named 'my-layer'. The response is awaited and stored in `resp`. ```javascript const resp = await client.getLayerVersion('my-layer', 3); ``` -------------------------------- ### STS example Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/configuration.md Creates a client in STS mode by prefixing accessKeyID with 'STS'. The securityToken is required in this mode and is sent as the x-fc-security-token header on every request. ```javascript const stsClient = new FCClient('1234567890', { accessKeyID: 'STS.xxxx', // prefix "STS" enables token mode accessKeySecret: '...', securityToken: 'CAIS...', // required in STS mode region: 'cn-shanghai' }); // every request carries: x-fc-security-token: ``` -------------------------------- ### putFunctionAsyncConfig usage example Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-scaling.md Example call to `putFunctionAsyncConfig` with a service name, function name, qualifier 'LATEST', and an options object specifying `maxAsyncEventAgeInSeconds`, `maxAsyncRetryAttempts`, and a `destinationConfig` for failure handling. ```javascript const resp = await client.putFunctionAsyncConfig('my-service', 'handler', 'LATEST', { maxAsyncEventAgeInSeconds: 3600, maxAsyncRetryAttempts: 3, destinationConfig: { onFailure: { destination: 'acs:fc:cn-shanghai:123:functions/my-service/fail-handler' } } }); ``` -------------------------------- ### listProvisionConfigs Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/index.md Lists provision configurations. This method sends a GET request to the provision-configs endpoint. ```APIDOC ## [GET] /provision-configs ### Description Lists provision configurations. ### Method GET ### Endpoint /provision-configs ### Parameters #### Query Parameters - **options** (object) - Optional - Query options (e.g., pagination). #### Headers - **headers** (object) - Optional - Additional HTTP headers. ### Request Example ```json {} ``` ### Response #### Success Response (200) - **provisionConfigs** (array) - List of provision configuration objects. #### Response Example ```json { "provisionConfigs": [] } ``` ``` -------------------------------- ### listServices: Expand tags and GET /services Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-services.md GETs /services with optional query parameters. Expands an options.tags object into tag_= query parameters and removes the tags key. Returns a Promise of { headers, data } where data.services is the service list and data.nextToken supports paging. ```javascript listServices(options = {}, headers) { if (options.tags !== undefined) { for (var k in options.tags) { if (Object.prototype.hasOwnProperty.call(options.tags, k)) { options[`tag_${k}`] = options.tags[k]; } } delete options.tags; } return this.get('/services', options, headers); } ``` ```javascript const resp = await client.listServices({ limit: 20, tags: { env: 'prod' } }); for (const svc of resp.data.services) console.log(svc.serviceName); ``` -------------------------------- ### Example usage of instanceExec Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-scaling.md Shows how to call instanceExec with custom command and hooks, send a stdin frame, and close the session after a timeout. ```javascript const session = await client.instanceExec('my-service', 'handler', 'LATEST', 'i-xxx', { command: '/bin/sh' }, { onStdout: (data) => process.stdout.write(Buffer.from(data)), onStderr: (data) => process.stderr.write(Buffer.from(data)), onError: (err) => console.error('exec error', err) }); session.sendMessage(new TextEncoder().encode('ls -la\n')); // stdin frame, type 0 setTimeout(() => session.close(), 5000); ``` -------------------------------- ### Catch file-too-large error when creating function Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/errors.md Example of catching the error thrown when the zip file is too large for the temp code bucket. Checks if the error message starts with 'the size of file'. ```javascript try { await client.createFunction('svc', { functionName: 'f', withoutCodeLimit: true, code: { zipFile: '/tmp/huge.zip' } }); } catch (err) { if (err.message.startsWith('the size of file')) { // zip too large for temp bucket } } ``` -------------------------------- ### Example: listProvisionConfigs call Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-scaling.md Shows how to call listProvisionConfigs with serviceName and qualifier query parameters. The response is a promise resolving to { headers, data }. ```javascript const resp = await client.listProvisionConfigs({ serviceName: 'my-service', qualifier: 'v1' }); ``` -------------------------------- ### getTempBucketToken() Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/index.md Gets a temporary token for accessing the temporary bucket. No parameters are required. ```APIDOC ## getTempBucketToken() ### Description Gets a temporary token for accessing the temporary bucket. No parameters are required. ### Method GET ### Endpoint GET /tempBucketToken ### Parameters None ### Request Example ```javascript const response = await client.getTempBucketToken(); ``` ### Response #### Success Response (200) - **token** (object) - Temporary access token #### Response Example ```json { "accessKeyId": "...", "accessKeySecret": "...", "securityToken": "..." } ``` ``` -------------------------------- ### getSignature usage example Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client.md Generates a signature for a GET request to the services endpoint. The headers include the current UTC date and the host. The output is a string like 'FC LTAI...:'. ```javascript const signature = FCClient.getSignature( 'LTAI...', 'secret', 'GET', '/2016-08-15/services', { date: new Date().toUTCString(), host: '123.fc.aliyuncs.com' }, null ); // "FC LTAI...:" ``` -------------------------------- ### Client instantiation example Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client.md Creates a Client with an account ID and configuration. Requires accessKeyID, accessKeySecret, and region; secure enables HTTPS; timeout overrides the 60s default; headers are passed through. ```javascript const FCClient = require('@alicloud/fc2'); const client = new FCClient('1234567890', { accessKeyID: 'LTAI...', accessKeySecret: 'secret', region: 'cn-shanghai', secure: true, timeout: 30000, headers: { 'x-fc-invocation-type': 'Async' } }); ``` -------------------------------- ### getAccountSettings usage example Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-tags-layers-account.md Retrieves account settings and logs the available availability zones from `resp.data.availableAZs`. ```javascript const resp = await client.getAccountSettings(); console.log(resp.data.availableAZs); ``` -------------------------------- ### listOnDemandConfigs usage example Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-scaling.md Calls listOnDemandConfigs with a limit of 20 to retrieve a list of on-demand configs. ```javascript const resp = await client.listOnDemandConfigs({ limit: 20 }); ``` -------------------------------- ### listOnDemandConfigs Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/index.md Lists on-demand configurations. This method sends a GET request to the on-demand-configs endpoint. ```APIDOC ## [GET] /on-demand-configs ### Description Lists on-demand configurations. ### Method GET ### Endpoint /on-demand-configs ### Parameters #### Query Parameters - **options** (object) - Optional - Query options (e.g., pagination). #### Headers - **headers** (object) - Optional - Additional HTTP headers. ### Request Example ```json {} ``` ### Response #### Success Response (200) - **onDemandConfigs** (array) - List of on-demand configuration objects. #### Response Example ```json { "onDemandConfigs": [] } ``` ``` -------------------------------- ### GET /custom-domains Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/endpoints.md Lists custom domains with optional pagination and filtering. Supports query parameters for limiting results, prefix matching, start key, and next token for pagination. ```APIDOC ## [GET] /custom-domains ### Description Lists custom domains with optional pagination and filtering. Supports query parameters for limiting results, prefix matching, start key, and next token for pagination. ### Method GET ### Endpoint /custom-domains ### Parameters #### Query Parameters - **limit** (integer) - Optional - Maximum number of domains to return. - **prefix** (string) - Optional - Filter domains by name prefix. - **startKey** (string) - Optional - Start key for pagination. - **nextToken** (string) - Optional - Token for the next page of results. ### Request Example GET /custom-domains?limit=10&prefix=api ### Response #### Success Response (200) - **domains** (array) - List of custom domains. - **nextToken** (string) - Token for the next page. #### Response Example { "domains": [ { "domainName": "example.com" } ], "nextToken": "abc123" } ``` -------------------------------- ### listFunctionAsyncConfigs Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/index.md Lists async configurations for a function. This method sends a GET request to the async-invoke-configs endpoint. ```APIDOC ## [GET] .../async-invoke-configs ### Description Lists async configurations for a function. ### Method GET ### Endpoint .../async-invoke-configs ### Parameters #### Path Parameters - **serviceName** (string) - Required - The name of the service. - **functionName** (string) - Required - The name of the function. #### Query Parameters - **options** (object) - Optional - Query options (e.g., pagination). #### Headers - **headers** (object) - Optional - Additional HTTP headers. ### Request Example ```json {} ``` ### Response #### Success Response (200) - **asyncConfigs** (array) - List of async configuration objects. #### Response Example ```json { "asyncConfigs": [] } ``` ``` -------------------------------- ### invokeFunction raw buffer and error handling example Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-functions.md Invokes a function with `rawBuf: true` to get a raw Buffer response, and demonstrates error handling by checking `err.name` and logging `err.code`, `err.message`, and `err.requestid`. ```javascript try { const resp = await client.invokeFunction('my-service', 'handler', 'event', {}, 'LATEST', { rawBuf: true }); console.log(resp.data); // Buffer } catch (err) { if (err.name === 'FCStateMachineStoppedError' /* example code */) { // handle specific FC error code } console.error(err.code, err.message, err.requestid); } ``` -------------------------------- ### instanceExec method implementation Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-scaling.md Establishes a WebSocket connection to execute a command in a function instance. Supports configurable query parameters (command, tty, stdin, stdout, stderr, idleTimeout) and hooks for close, error, stdout, and stderr events. Sends a ping every 5000 ms and returns an object with websocket, close, and sendMessage methods. ```javascript async instanceExec( serviceName, functionName, qualifier = '', instanceId, options = {}, hooks = {} ) { const messageStdin = 0; const messageStdout = 1; const messageStderr = 2; var queries = { command: '/bin/bash', tty: true, stdin: true, stdout: true, stderr: false, idleTimeout: 120 }; for (var key of Object.keys(queries)) { if (typeof options[key] !== 'undefined') { queries[key] = options[key]; } } const { onClose = () => { }, onError = () => { }, onStdout = () => { }, onStderr = () => { } } = hooks; const ws = this.websocket( `/services/${getServiceName( serviceName, qualifier )}/functions/${functionName}/instances/${instanceId}/exec`, queries ); const ticker = setInterval(function () { try { ws.ping(); } catch (e) { ws.close(); } }, 5000); ws.on('unexpected-response', function (req, incoming) { var data = []; incoming.on('data', function (chunk) { data = data.concat(chunk); }); incoming.on('end', function () { const msg = JSON.parse(data.toString()); const err = new Error(msg.ErrorMessage); onError(err); ws.close(); }); }); ws.on('close', (err) => { clearInterval(ticker); onClose(err); }); ws.on('error', (code, reason) => onError(code, reason)); ws.on('ping', (data) => ws.pong(data)); ws.on('message', (message) => { if (!!message && message.length >= 2) { const messageType = message[0]; const data = message.slice(1); if (messageType === messageStdout && onStdout) { onStdout(data); } else if (messageType === messageStderr && onStderr) { onStderr(data); } } }); await (async () => { new Promise((resolve) => (ws.onopen = resolve)); }); return { websocket: ws, close: () => ws.close(), sendMessage: (data) => { if (!(data instanceof Uint8Array)) { throw new Error('data must be Uint8Array'); } const messageArray = new Uint8Array(data.length); messageArray.set(data); ws.send(messageArray); } }; } ``` -------------------------------- ### Example: listReservedCapacities call Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-scaling.md Shows how to call listReservedCapacities with a limit query parameter. The response is a promise resolving to { headers, data }. ```javascript const resp = await client.listReservedCapacities({ limit: 10 }); ``` -------------------------------- ### listInstances usage example Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-scaling.md Shows how to call listInstances with a service name, function name, and qualifier 'LATEST'. The response data contains an instances array; the first instance's ID is accessed via `resp.data.instances[0].instanceId`. ```javascript const resp = await client.listInstances('my-service', 'handler', 'LATEST'); const instanceId = resp.data.instances[0].instanceId; ``` -------------------------------- ### getAlias usage example Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-services.md Calls `getAlias` with a service name and alias name to fetch alias details. ```javascript const resp = await client.getAlias('my-service', 'prod'); ``` -------------------------------- ### deleteCustomDomain usage example Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-triggers.md Example call to delete a custom domain named 'api.example.com'. ```javascript const resp = await client.deleteCustomDomain('api.example.com'); ``` -------------------------------- ### Example: basic and custom endpoint client Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/configuration.md Shows two client configurations: one with secure, timeout, and headers options, and another with a custom endpoint for private deployments. The custom endpoint overrides the default and sets host to the endpoint's hostname. ```javascript const client = new FCClient('1234567890', { accessKeyID: 'LTAI...', accessKeySecret: '...', region: 'cn-shanghai', secure: true, // https internal: false, // public network timeout: 30000, // 30s request timeout headers: { // applied to every request 'x-fc-invocation-type': 'Async' } }); // custom endpoint (e.g. private deployment or VPC proxy) const custom = new FCClient('1234567890', { accessKeyID: 'LTAI...', accessKeySecret: '...', region: 'cn-shanghai', endpoint: 'https://fc.example.internal' }); console.log(custom.host); // 'fc.example.internal' ``` -------------------------------- ### tagResource usage example Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-tags-layers-account.md Example call to tagResource with a resource ARN and tag object. ```javascript const resp = await client.tagResource( 'acs:fc:cn-shanghai:123:services/my-service', { env: 'prod', team: 'platform' } ); ``` -------------------------------- ### updateCustomDomain usage example Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-triggers.md Example call to update the protocol of a custom domain to 'HTTP,HTTPS'. ```javascript const resp = await client.updateCustomDomain('api.example.com', { protocol: 'HTTP,HTTPS' }); ``` -------------------------------- ### Usage example for getAccountConfigs Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-functions.md Shows how to call getAccountConfigs with a config object requesting the CodeSizeLimit. The returned data's CodeSizeLimit is logged to the console. ```javascript const { data } = await client.getAccountConfigs({ config: ['CodeSizeLimit'] }); console.log(data.CodeSizeLimit); ``` -------------------------------- ### listInstances method implementation Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-scaling.md Defines the listInstances method on the client. It performs a GET request to `/services//functions//instances` with optional query-string parameters and custom headers. Returns a Promise of `{ headers, data }` where `data.instances` is a list of running instances. ```javascript listInstances( serviceName, functionName, qualifier, options = {}, headers = {} ) { return this.get( `/services/${getServiceName( serviceName, qualifier )}/functions/${functionName}/instances`, options, headers ); } ``` -------------------------------- ### deleteTrigger usage example Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-triggers.md Example call to deleteTrigger with service, function, and trigger names. The response is stored in resp. ```javascript const resp = await client.deleteTrigger('my-service', 'handler', 'every-minute'); ``` -------------------------------- ### new Client(accountid, config) Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client.md Creates a new Client instance for the Aliyun Function Compute OpenAPI. Requires an Aliyun account ID and a configuration object with credentials and region. ```APIDOC ## Constructor: new Client(accountid, config) ### Description Creates a new Client instance for the Aliyun Function Compute OpenAPI. Requires an Aliyun account ID and a configuration object with credentials and region. ### Parameters - **accountid** (string) - Required - Aliyun account ID. Throws `TypeError` if falsy. - **config** (object) - Required - Configuration object. Throws `TypeError` if falsy. ### Config Properties - **accessKeyID** (string) - Required - Access key ID. Throws `TypeError` if missing. - **accessKeySecret** (string) - Required - Access key secret. Throws `TypeError` if missing. - **region** (string) - Required - Region name. Throws `TypeError` if missing. - **securityToken** (string) - Optional - Required if `accessKeyID` starts with `"STS"`. Throws `TypeError` if missing in that case. - **secure** (boolean) - Optional - If true, uses HTTPS; otherwise HTTP. - **internal** (boolean) - Optional - If true, uses internal endpoint. - **endpoint** (string) - Optional - Custom endpoint URL. Overrides default endpoint. - **timeout** (number) - Optional - Timeout in milliseconds. Default: 60000. - **headers** (object) - Optional - Additional headers. ### Example ```js const FCClient = require('@alicloud/fc2'); const client = new FCClient('1234567890', { accessKeyID: 'LTAI...', accessKeySecret: 'secret', region: 'cn-shanghai', secure: true, timeout: 30000, headers: { 'x-fc-invocation-type': 'Async' } }); ``` ### Throws - **TypeError** - If `accountid` not passed. - **TypeError** - If `config` not passed. - **TypeError** - If `config.accessKeyID` missing. - **TypeError** - If `config.accessKeySecret` missing. - **TypeError** - If `config.region` missing. - **TypeError** - If `accessKeyID` starts with `"STS"` but `config.securityToken` missing. ``` -------------------------------- ### updateTrigger usage example Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-triggers.md Example call to updateTrigger with a trigger configuration for a fixed-rate cron expression. The response is stored in resp. ```javascript const resp = await client.updateTrigger('my-service', 'handler', 'every-minute', { triggerConfig: { payload: 'fixed-rate', cronExpression: '0 */5 * * * *' } }); ``` -------------------------------- ### Run tests Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/README.md Run the test suite with required environment variables. ```bash ACCOUNT_ID= ACCESS_KEY_ID= ACCESS_KEY_SECRET= make test ``` -------------------------------- ### Example: raw-buffer response mode Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client.md Shows how to invoke a function with rawBuf: true to receive binary output as a Buffer. The response data is a Buffer, not a parsed object. ```javascript // Raw-buffer response mode (binary function output) const resp = await client.request('POST', '/services/my-svc/functions/my-fn/invocations', null, 'event', {}, { rawBuf: true }); console.log(resp.data); // Buffer ``` -------------------------------- ### untagResource usage example Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-tags-layers-account.md Example calls to untagResource: one removing specific tag keys, and an all-tags variant with all=true. ```javascript const resp = await client.untagResource('acs:fc:cn-shanghai:123:services/my-service', ['env']); // all-tags variant const resp2 = await client.untagResource('acs:fc:cn-shanghai:123:services/my-service', [], true); ``` -------------------------------- ### instanceExec(serviceName, functionName, qualifier, instanceId, options, hooks) Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/configuration.md Executes a command in a specific instance of a function. The options parameter overrides exec query defaults, and hooks provide callbacks for lifecycle events. ```APIDOC ## instanceExec(serviceName, functionName, qualifier, instanceId, options, hooks) ### Description Executes a command in a specific instance of a function. The `options` parameter overrides exec query defaults, and `hooks` provide callbacks for lifecycle events. ### Method `instanceExec` ### Parameters - **serviceName** (string) - Required - Name of the service. - **functionName** (string) - Required - Name of the function. - **qualifier** (string) - Required - Function qualifier (e.g., version or alias). - **instanceId** (string) - Required - ID of the instance. - **options** (object) - Optional - Overrides exec query defaults. - **hooks** (object) - Optional - Callback hooks. - **hooks.onClose** (function) - Optional - Called when the connection closes. - **hooks.onError** (function) - Optional - Called on error. - **hooks.onStdout** (function) - Optional - Called with stdout data. - **hooks.onStderr** (function) - Optional - Called with stderr data. ### Response Returns the result of the exec operation. See [client-scaling.md](api-reference/client-scaling.md#async-instanceexec) for details. ``` -------------------------------- ### GET /services//tempCodeBucketToken Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/endpoints.md Gets a temporary code bucket token for a function. Used internally for large code uploads. ```APIDOC ## [GET] /services//tempCodeBucketToken ### Description Gets a temporary code bucket token for a function. Used internally for large code uploads. ### Method GET ### Endpoint /services//tempCodeBucketToken ### Parameters #### Path Parameters - **serviceName** (string) - Required - Name of the service. #### Query Parameters - **functionName** (string) - Required - Name of the function. - **instanceType** (string) - Optional - Instance type. ### Response #### Success Response (200) - **token** (string) - Temporary token. - **...** (any) - Additional token information. #### Response Example { "token": "temporary-token" } ``` -------------------------------- ### Example usage of publishLayerVersionForBigCode Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-tags-layers-account.md Calls publishLayerVersionForBigCode with a layer name and options including description and codeConfig with size and zipFilePath. The size is obtained from fs.statSync on the local zip file. ```javascript const resp = await client.publishLayerVersionForBigCode('my-layer', { description: 'big layer', codeConfig: { size: fs.statSync('/tmp/big.zip').size, zipFilePath: '/tmp/big.zip' } }); ``` -------------------------------- ### listLayers usage example Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-tags-layers-account.md Calls listLayers with options to fetch official layers with a limit of 20. The response data is not used in this example. ```javascript const resp = await client.listLayers({ official: true, limit: 20 }); ``` -------------------------------- ### getTrigger usage example Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-triggers.md Example call to getTrigger with a service name, function name, and trigger name. The response is awaited and stored in resp. ```javascript const resp = await client.getTrigger('my-service', 'handler', 'every-minute'); ``` -------------------------------- ### listProvisionConfigs method implementation Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-scaling.md Defines the listProvisionConfigs method on the Client class, which GETs /provision-configs with optional query parameters and headers. Returns a promise resolving to { headers, data } where data.provisionConfigs is a list. ```javascript listProvisionConfigs(options = {}, headers) { return this.get('/provision-configs', options, headers); } ``` -------------------------------- ### Usage example for getTempCodeBucketPermission Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-functions.md Shows how to call getTempCodeBucketPermission with a service name, function name, and instance type. The returned data includes ossBucket and codeSizeLimit, which are logged to the console. ```javascript const token = await client.getTempCodeBucketPermission('my-service', 'big-fn', 'e1'); console.log(token.data.ossBucket, token.data.codeSizeLimit); ``` -------------------------------- ### getLayerVersionByArn usage example Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-tags-layers-account.md Example call to getLayerVersionByArn, using a full ARN string. The ARN is URL-encoded automatically in the method. The response is awaited and stored in `resp`. ```javascript const arn = 'acs:fc:cn-shanghai:123:layers/my-layer/versions/3'; const resp = await client.getLayerVersionByArn(arn); ``` -------------------------------- ### deleteFunctionAsyncConfig usage example Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-scaling.md Example call to delete the async invoke configuration for a function named 'handler' in service 'my-service' with qualifier 'v1'. ```javascript const resp = await client.deleteFunctionAsyncConfig('my-service', 'handler', 'v1'); ``` -------------------------------- ### listProvisionConfigs(options, headers) Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-scaling.md Lists provision configs. This method sends a GET request to /provision-configs and returns a promise that resolves to an object containing headers and data, where data.provisionConfigs is the list of provision configs. ```APIDOC ## GET /provision-configs ### Description Lists provision configs. This method sends a GET request to /provision-configs and returns a promise that resolves to an object containing headers and data, where data.provisionConfigs is the list of provision configs. ### Method GET ### Endpoint /provision-configs ### Parameters #### Query Parameters - **limit** (number) - Optional - Limit the number of results. - **nextToken** (string) - Optional - Token for pagination. - **serviceName** (string) - Optional - The name of the service. - **qualifier** (string) - Optional - The qualifier (version or alias). ### Request Example ```js const resp = await client.listProvisionConfigs({ serviceName: 'my-service', qualifier: 'v1' }); ``` ### Response #### Success Response (200) - **headers** (object) - Response headers. - **data** (object) - Response body. - **provisionConfigs** (array) - List of provision configs. #### Response Example ```json { "headers": {}, "data": { "provisionConfigs": [] } } ``` ``` -------------------------------- ### listInstances(serviceName, functionName, qualifier, options, headers) Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-scaling.md Lists running instances of a function. This method sends a GET request to the specified endpoint and returns a promise with the response data containing the instances list. ```APIDOC ## [GET] /services//functions//instances ### Description Lists running instances of a function. This method sends a GET request to the specified endpoint and returns a promise with the response data containing the instances list. ### Method GET ### Endpoint `/services//functions//instances` ### Parameters #### Path Parameters - **serviceName** (string) - Required - Service name - **functionName** (string) - Required - Function name - **qualifier** (string) - Optional - Version/alias qualifier #### Query Parameters - **options** (object) - Optional - Query-string parameters #### Request Headers - **headers** (object) - Optional - Custom request headers ### Request Example ```js const resp = await client.listInstances('my-service', 'handler', 'LATEST'); ``` ### Response #### Success Response (200) - **data.instances** (array) - List of running instances #### Response Example ```js const instanceId = resp.data.instances[0].instanceId; ``` ``` -------------------------------- ### listTriggers usage example Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-triggers.md Example call to listTriggers with a service name, function name, and options object specifying a limit of 20. The response is awaited and stored in resp. ```javascript const resp = await client.listTriggers('my-service', 'handler', { limit: 20 }); ``` -------------------------------- ### putLayerACL usage example Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-tags-layers-account.md Example call to putLayerACL to set the layer's ACL to public. The `options` object contains the query parameter `public` set to true. ```javascript const resp = await client.putLayerACL('my-layer', { public: true }); ``` -------------------------------- ### listVersions method implementation Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-services.md Defines the listVersions method on the client. It GETs /services//versions with query options and custom headers. Returns a promise of { headers, data } where data.versions is a list. ```javascript listVersions(serviceName, options = {}, headers = {}) { return this.get(`/services/${serviceName}/versions`, options, headers); } ``` -------------------------------- ### Constructor call with config object Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/configuration.md Creates an FCClient instance using the constructor options object. The config object requires accessKeyID, accessKeySecret, and region; missing required fields throw a TypeError. Optional fields include secure, internal, endpoint, timeout, and headers. ```javascript const client = new FCClient(accountid, config); ``` -------------------------------- ### createService method Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-services.md Creates a service by POSTing to `/services` with the service name and optional fields (description, logConfig, role) merged into the body. Returns a promise resolving to `{ headers, data }` where data is a Service object. ```javascript createService(serviceName, options = {}, headers) { return this.post( '/services', Object.assign( { serviceName }, options ), headers ); } ``` -------------------------------- ### String-to-sign format (lib/helper.js) Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client.md Shows the structure of the string that is signed for request authentication. It includes the HTTP method, content-md5, content-type, date, canonical x-fc headers, and the path, followed by sorted query parameters when provided. ```text \n\n\n\n ``` -------------------------------- ### getFunction usage example Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-functions.md Shows how to call getFunction with a service name, function name, empty headers, and a qualifier. The response is awaited and stored in `resp`. ```javascript const resp = await client.getFunction('my-service', 'handler', {}, 'v1'); ``` -------------------------------- ### listFunctionAsyncConfigs method implementation Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-scaling.md Lists async invoke configurations for a function. Uses GET on `/services//functions//async-invoke-configs`. Note: no qualifier support in this method as written. Returns a Promise of `{ headers, data }` where `data.configs` is a list of async invoke configs. ```javascript listFunctionAsyncConfigs( serviceName, functionName, options = {}, headers = {} ) { return this.get( `/services/${serviceName}/functions/${functionName}/async-invoke-configs`, options, headers ); } ``` -------------------------------- ### listLayers Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/index.md Lists all layers. This method sends a GET request to the layers endpoint. ```APIDOC ## [GET] /layers ### Description Lists all layers. ### Method GET ### Endpoint /layers ### Parameters #### Query Parameters - **options** (object) - Optional - Query options (e.g., pagination). #### Headers - **headers** (object) - Optional - Additional HTTP headers. ### Request Example ```json {} ``` ### Response #### Success Response (200) - **layers** (array) - List of layer objects. #### Response Example ```json { "layers": [] } ``` ``` -------------------------------- ### getAccountSettings Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/index.md Retrieves account settings. This method sends a GET request to the account-settings endpoint. ```APIDOC ## [GET] /account-settings ### Description Retrieves account settings. ### Method GET ### Endpoint /account-settings ### Parameters #### Query Parameters - **options** (object) - Optional - Query options. #### Headers - **headers** (object) - Optional - Additional HTTP headers. ### Request Example ```json {} ``` ### Response #### Success Response (200) - **accountSettings** (object) - The account settings object. #### Response Example ```json { "accountSettings": {} } ``` ``` -------------------------------- ### listFunctions usage example Source: https://github.com/aliyun/fc-nodejs-sdk/blob/master/_autodocs/api-reference/client-functions.md Shows how to call listFunctions with a service name and options to limit the result count. The response is awaited and stored in `resp`. ```javascript const resp = await client.listFunctions('my-service', { limit: 50 }); ```