@alipay/faas-server-sdk
Advanced tools
Comparing version 1.0.10 to 1.1.0-alpha.0
import { AlipayContext } from '@alipay/faas-server-utils'; | ||
import { Database } from './Database'; | ||
import { MySQL } from './MySQL'; | ||
import { Storage } from './Storage'; | ||
import type { OpenapiFunction } from './Openapi'; | ||
import type { CallFunctionParam, CloudInitOptions, DownloadFileParam, UploadFileParam } from './types'; | ||
import { CallFunctionResult, DeleteFileResult, DownloadFileResult, GetDatabaseOptions, GetTempFileURLResult, UploadFileResult } from './types'; | ||
import type { CallFunctionParam, CloudInitOptions, DownloadFileParam, UploadFileParam, CallFunctionResult, DeleteFileResult, DownloadFileResult, GetDatabaseOptions, GetTempFileURLResult, UploadFileResult } from './types'; | ||
export declare function initRuntimeEnv(env: Record<string, string>): void; | ||
@@ -18,2 +18,3 @@ export declare class Cloud { | ||
get openapi(): OpenapiFunction; | ||
getStorage(): Storage; | ||
uploadFile(param: UploadFileParam): Promise<UploadFileResult>; | ||
@@ -20,0 +21,0 @@ downloadFile(param: DownloadFileParam): Promise<DownloadFileResult>; |
@@ -1,1 +0,1 @@ | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Cloud=exports.initRuntimeEnv=void 0;const faas_server_utils_1=require("@alipay/faas-server-utils"),callFunction_1=require("./callFunction"),constant_1=require("./constant"),Database_1=require("./Database"),MySQL_1=require("./MySQL"),Openapi_1=require("./Openapi"),Storage_1=require("./Storage"),utils_1=require("./utils"),runtimeEnv={RUNTIME_ACCESS_KEY:process.env.RUNTIME_ACCESS_KEY||"",RUNTIME_SECRET_KEY:process.env.RUNTIME_SECRET_KEY||"",RUNTIME_ENV_ID:process.env.RUNTIME_ENV_ID||"",RUNTIME_FUNCTION_NAME:process.env.RUNTIME_FUNCTION_NAME||"",RUNTIME_FUNCTION_GATEWAY_ENDPOINT:process.env.RUNTIME_FUNCTION_GATEWAY_ENDPOINT||"",RUNTIME_FUNCTION_INSTANCE_ID:process.env.RUNTIME_FUNCTION_INSTANCE_ID||"",RUNTIME_MONGO_CLUSTER_ENDPOINT:process.env.RUNTIME_MONGO_CLUSTER_ENDPOINT||"",RUNTIME_MONGO_DATABASE_NAME:process.env.RUNTIME_MONGO_DATABASE_NAME||"",RUNTIME_OSS_ENDPOINT:process.env.RUNTIME_OSS_ENDPOINT||"",RUNTIME_MYSQL_ENDPOINT:process.env.RUNTIME_MYSQL_ENDPOINT||""};function initRuntimeEnv(e){Object.assign(runtimeEnv,e)}exports.initRuntimeEnv=initRuntimeEnv;class Cloud{#t;#e;#E;#n;constructor(){this.#t={secretId:runtimeEnv.RUNTIME_ACCESS_KEY,secretKey:runtimeEnv.RUNTIME_SECRET_KEY,fromEnvId:runtimeEnv.RUNTIME_ENV_ID,toEnvId:runtimeEnv.RUNTIME_ENV_ID,functionName:runtimeEnv.RUNTIME_FUNCTION_NAME,functionGatewayEndpoint:runtimeEnv.RUNTIME_FUNCTION_GATEWAY_ENDPOINT,functionInstanceId:runtimeEnv.RUNTIME_FUNCTION_INSTANCE_ID,functionDatabaseEndpoint:runtimeEnv.RUNTIME_MONGO_CLUSTER_ENDPOINT,functionDatabaseName:runtimeEnv.RUNTIME_MONGO_DATABASE_NAME,functionStorageEndpoint:runtimeEnv.RUNTIME_OSS_ENDPOINT,functionMysqlEndpoint:runtimeEnv.RUNTIME_MYSQL_ENDPOINT}}refreshConfig(){runtimeEnv.RUNTIME_ACCESS_KEY&&(this.#t.secretId=runtimeEnv.RUNTIME_ACCESS_KEY),runtimeEnv.RUNTIME_SECRET_KEY&&(this.#t.secretKey=runtimeEnv.RUNTIME_SECRET_KEY),runtimeEnv.RUNTIME_ENV_ID&&(this.#t.fromEnvId=runtimeEnv.RUNTIME_ENV_ID,this.#t.toEnvId||(this.#t.toEnvId=runtimeEnv.RUNTIME_ENV_ID)),runtimeEnv.RUNTIME_FUNCTION_NAME&&(this.#t.functionName=runtimeEnv.RUNTIME_FUNCTION_NAME),runtimeEnv.RUNTIME_FUNCTION_GATEWAY_ENDPOINT&&(this.#t.functionGatewayEndpoint=runtimeEnv.RUNTIME_FUNCTION_GATEWAY_ENDPOINT),runtimeEnv.RUNTIME_FUNCTION_INSTANCE_ID&&(this.#t.functionInstanceId=runtimeEnv.RUNTIME_FUNCTION_INSTANCE_ID),runtimeEnv.RUNTIME_MONGO_CLUSTER_ENDPOINT&&(this.#t.functionDatabaseEndpoint=runtimeEnv.RUNTIME_MONGO_CLUSTER_ENDPOINT),runtimeEnv.RUNTIME_MONGO_DATABASE_NAME&&(this.#t.functionDatabaseName=runtimeEnv.RUNTIME_MONGO_DATABASE_NAME),runtimeEnv.RUNTIME_OSS_ENDPOINT&&(this.#t.functionStorageEndpoint=runtimeEnv.RUNTIME_OSS_ENDPOINT),runtimeEnv.RUNTIME_MYSQL_ENDPOINT&&(this.#t.functionMysqlEndpoint=runtimeEnv.RUNTIME_MYSQL_ENDPOINT)}init(t){const N=this.#_(t?.env);N&&(this.#t.toEnvId=N),t?.envId&&(this.#t.toEnvId=t.envId),t?.timeout!==void 0&&(this.#t.timeout=(0,utils_1.validateTimeout)(t.timeout))}getAlipayContext(){return(0,faas_server_utils_1.getAlipayContext)()}async callFunction(t){const{config:N,...E}=t||{},n=this.#i(N?.env);return await(0,callFunction_1.callFunction)(n,E)}database(t){const N=this.#i(t?.env);return new Database_1.Database({...N,throwOnNotFound:t?.throwOnNotFound!==!1,timeout:(0,utils_1.validateTimeout)(t?.timeout??N.timeout)})}mysql(){return this.#E||(this.#E=new MySQL_1.MySQL(this.#t)),this.#E}get openapi(){return this.#n||(this.#n=(0,Openapi_1.createOpenapi)(this.#t)),this.#n}#N(){return this.#e||(this.#e=new Storage_1.Storage(this.#t)),this.#e}async uploadFile(t){return await this.#N().uploadFile(t)}async downloadFile(t){return await this.#N().downloadFile(t)}async deleteFile(t){return await this.#N().deleteFile(t)}async getTempFileURL(t){return await this.#N().getTempFileURL(t)}#i(t){const N=this.#_(t);return N?{...this.#t,toEnvId:N}:this.#t}#_(t){return t&&typeof t=="string"?t:t&&t===constant_1.DYNAMIC_CURRENT_ENV?runtimeEnv.RUNTIME_ENV_ID:null}}exports.Cloud=Cloud; | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Cloud=exports.initRuntimeEnv=void 0;const faas_server_utils_1=require("@alipay/faas-server-utils"),callFunction_1=require("./callFunction"),constant_1=require("./constant"),Database_1=require("./Database"),MySQL_1=require("./MySQL"),Openapi_1=require("./Openapi"),Storage_1=require("./Storage"),utils_1=require("./utils"),runtimeEnv={RUNTIME_ACCESS_KEY:process.env.RUNTIME_ACCESS_KEY||"",RUNTIME_SECRET_KEY:process.env.RUNTIME_SECRET_KEY||"",RUNTIME_ENV_ID:process.env.RUNTIME_ENV_ID||"",RUNTIME_FUNCTION_NAME:process.env.RUNTIME_FUNCTION_NAME||"",RUNTIME_FUNCTION_GATEWAY_ENDPOINT:process.env.RUNTIME_FUNCTION_GATEWAY_ENDPOINT||"",RUNTIME_FUNCTION_INSTANCE_ID:process.env.RUNTIME_FUNCTION_INSTANCE_ID||"",RUNTIME_MONGO_CLUSTER_ENDPOINT:process.env.RUNTIME_MONGO_CLUSTER_ENDPOINT||"",RUNTIME_MONGO_DATABASE_NAME:process.env.RUNTIME_MONGO_DATABASE_NAME||"",RUNTIME_OSS_ENDPOINT:process.env.RUNTIME_OSS_ENDPOINT||"",RUNTIME_MYSQL_ENDPOINT:process.env.RUNTIME_MYSQL_ENDPOINT||""};function initRuntimeEnv(N){Object.assign(runtimeEnv,N)}exports.initRuntimeEnv=initRuntimeEnv;class Cloud{#t;#e;#N;#E;constructor(){this.#t={secretId:runtimeEnv.RUNTIME_ACCESS_KEY,secretKey:runtimeEnv.RUNTIME_SECRET_KEY,fromEnvId:runtimeEnv.RUNTIME_ENV_ID,toEnvId:runtimeEnv.RUNTIME_ENV_ID,functionName:runtimeEnv.RUNTIME_FUNCTION_NAME,functionGatewayEndpoint:runtimeEnv.RUNTIME_FUNCTION_GATEWAY_ENDPOINT,functionInstanceId:runtimeEnv.RUNTIME_FUNCTION_INSTANCE_ID,functionDatabaseEndpoint:runtimeEnv.RUNTIME_MONGO_CLUSTER_ENDPOINT,functionDatabaseName:runtimeEnv.RUNTIME_MONGO_DATABASE_NAME,functionStorageEndpoint:runtimeEnv.RUNTIME_OSS_ENDPOINT,functionMysqlEndpoint:runtimeEnv.RUNTIME_MYSQL_ENDPOINT,timeout:1e4}}refreshConfig(){runtimeEnv.RUNTIME_ACCESS_KEY&&(this.#t.secretId=runtimeEnv.RUNTIME_ACCESS_KEY),runtimeEnv.RUNTIME_SECRET_KEY&&(this.#t.secretKey=runtimeEnv.RUNTIME_SECRET_KEY),runtimeEnv.RUNTIME_ENV_ID&&(this.#t.fromEnvId=runtimeEnv.RUNTIME_ENV_ID,this.#t.toEnvId||(this.#t.toEnvId=runtimeEnv.RUNTIME_ENV_ID)),runtimeEnv.RUNTIME_FUNCTION_NAME&&(this.#t.functionName=runtimeEnv.RUNTIME_FUNCTION_NAME),runtimeEnv.RUNTIME_FUNCTION_GATEWAY_ENDPOINT&&(this.#t.functionGatewayEndpoint=runtimeEnv.RUNTIME_FUNCTION_GATEWAY_ENDPOINT),runtimeEnv.RUNTIME_FUNCTION_INSTANCE_ID&&(this.#t.functionInstanceId=runtimeEnv.RUNTIME_FUNCTION_INSTANCE_ID),runtimeEnv.RUNTIME_MONGO_CLUSTER_ENDPOINT&&(this.#t.functionDatabaseEndpoint=runtimeEnv.RUNTIME_MONGO_CLUSTER_ENDPOINT),runtimeEnv.RUNTIME_MONGO_DATABASE_NAME&&(this.#t.functionDatabaseName=runtimeEnv.RUNTIME_MONGO_DATABASE_NAME),runtimeEnv.RUNTIME_OSS_ENDPOINT&&(this.#t.functionStorageEndpoint=runtimeEnv.RUNTIME_OSS_ENDPOINT),runtimeEnv.RUNTIME_MYSQL_ENDPOINT&&(this.#t.functionMysqlEndpoint=runtimeEnv.RUNTIME_MYSQL_ENDPOINT)}init(t){const e=this.#i(t?.env);e&&(this.#t.toEnvId=e),t?.envId&&(this.#t.toEnvId=t.envId),t?.timeout!==void 0&&(this.#t.timeout=(0,utils_1.validateTimeout)(t.timeout))}getAlipayContext(){return(0,faas_server_utils_1.getAlipayContext)()}async callFunction(t){const{config:e,...E}=t||{},n=this.#n(e?.env);return await(0,callFunction_1.callFunction)(n,E)}database(t){const e=this.#n(t?.env);return new Database_1.Database({...e,throwOnNotFound:t?.throwOnNotFound!==!1,timeout:(0,utils_1.validateTimeout)(t?.timeout??e.timeout)})}mysql(){return this.#N||(this.#N=new MySQL_1.MySQL(this.#t)),this.#N}get openapi(){return this.#E||(this.#E=(0,Openapi_1.createOpenapi)(this.#t)),this.#E}getStorage(){return this.#e||(this.#e=new Storage_1.Storage(this.#t)),this.#e}async uploadFile(t){return await this.getStorage().uploadFile(t)}async downloadFile(t){return await this.getStorage().downloadFile(t)}async deleteFile(t){return await this.getStorage().deleteFile(t)}async getTempFileURL(t){return await this.getStorage().getTempFileURL(t)}#n(t){const e=this.#i(t);return e?{...this.#t,toEnvId:e}:this.#t}#i(t){return t&&typeof t=="string"?t:t&&t===constant_1.DYNAMIC_CURRENT_ENV?runtimeEnv.RUNTIME_ENV_ID:null}}exports.Cloud=Cloud; |
export declare const OPENAPI_VERSION = "1.0"; | ||
export declare const DYNAMIC_CURRENT_ENV: unique symbol; | ||
export declare const SDK_USER_AGENT: string; |
@@ -1,1 +0,1 @@ | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.DYNAMIC_CURRENT_ENV=exports.OPENAPI_VERSION=void 0,exports.OPENAPI_VERSION="1.0",exports.DYNAMIC_CURRENT_ENV=Symbol.for("faas#dynamicCurrentEnv"); | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.SDK_USER_AGENT=exports.DYNAMIC_CURRENT_ENV=exports.OPENAPI_VERSION=void 0;const urllib_1=require("urllib"),{version}=require("../package.json");exports.OPENAPI_VERSION="1.0",exports.DYNAMIC_CURRENT_ENV=Symbol.for("faas#dynamicCurrentEnv"),exports.SDK_USER_AGENT=`faas-server-sdk/${version} ${urllib_1.USER_AGENT}`; |
@@ -0,1 +1,4 @@ | ||
/// <reference types="node" /> | ||
import type { IncomingHttpHeaders } from 'node:http'; | ||
import type { HttpMethod } from 'urllib'; | ||
import { Command } from '@alipay/faas-db-builder'; | ||
@@ -9,2 +12,3 @@ import { CollectionDescription, DatabaseCloudConfig, DeleteResult } from '../types'; | ||
collection(collectionName: string): Collection; | ||
requestRaw(method: HttpMethod, urlpath: string, data: object, headers: IncomingHttpHeaders): Promise<import("urllib").HttpClientResponse<unknown>>; | ||
createCollection(collectionName: string): Promise<CollectionDescription>; | ||
@@ -11,0 +15,0 @@ getCollection(collectionName: string): Promise<CollectionDescription | null>; |
@@ -1,1 +0,1 @@ | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Database=void 0;const faas_db_builder_1=require("@alipay/faas-db-builder"),errors_1=require("../errors"),middlewares_1=require("../requester/middlewares"),Collection_1=require("./Collection");class Database{#t;command;#s;constructor(t){this.#t=t,this.command=new faas_db_builder_1.Command,this.#s=new faas_db_builder_1.MongoBuilder}collection(t){return new Collection_1.Collection(this.#t,t)}#o(){return`${this.#t.functionDatabaseEndpoint}/${this.#t.functionDatabaseName||"faas"}`}#e(t){return`${this.#o()}/${t}`}async createCollection(t){const s="PUT",o=this.#e(t),e=await middlewares_1.HttpRequester.database.request(s,o,{},{},{cloudConfig:this.#t});if(!e.succeed)throw errors_1.errors.CALL_DATABASE_ERR(e);return e.data}async getCollection(t){const s="GET",o=this.#e(t),e=await middlewares_1.HttpRequester.database.request(s,o,{},{},{cloudConfig:this.#t});if(!e.succeed)throw errors_1.errors.CALL_DATABASE_ERR(e);return e.data}async listCollection(t,s){const o="POST",e=`${this.#o()}?list`,{options:a}=this.#s.listCollection(t,s),r=await middlewares_1.HttpRequester.database.request(o,e,a,{},{cloudConfig:this.#t});if(!r.succeed)throw errors_1.errors.CALL_DATABASE_ERR(r);return r.data}async deleteCollection(t){const s="DELETE",o=this.#e(t),e=await middlewares_1.HttpRequester.database.request(s,o,{},{},{cloudConfig:this.#t});if(!e.succeed)throw errors_1.errors.CALL_DATABASE_ERR(e);return e.data}}exports.Database=Database; | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Database=void 0;const faas_db_builder_1=require("@alipay/faas-db-builder"),errors_1=require("../errors"),middlewares_1=require("../requester/middlewares"),Collection_1=require("./Collection");class Database{#t;command;#s;constructor(t){this.#t=t,this.command=new faas_db_builder_1.Command,this.#s=new faas_db_builder_1.MongoBuilder}collection(t){return new Collection_1.Collection(this.#t,t)}#o(){return`${this.#t.functionDatabaseEndpoint}/${this.#t.functionDatabaseName||"faas"}`}#e(t){return`${this.#o()}/${t}`}async requestRaw(t,s,o,e){const a=`${this.#t.functionDatabaseEndpoint}${s}`,{res:r}=await middlewares_1.HttpRequester.database.requestRaw(t,a,o,e,{cloudConfig:this.#t});return r}async createCollection(t){const s="PUT",o=this.#e(t),e=await middlewares_1.HttpRequester.database.request(s,o,{},{},{cloudConfig:this.#t});if(!e.succeed)throw errors_1.errors.CALL_DATABASE_ERR(e);return e.data}async getCollection(t){const s="GET",o=this.#e(t),e=await middlewares_1.HttpRequester.database.request(s,o,{},{},{cloudConfig:this.#t});if(!e.succeed)throw errors_1.errors.CALL_DATABASE_ERR(e);return e.data}async listCollection(t,s){const o="POST",e=`${this.#o()}?list`,{options:a}=this.#s.listCollection(t,s),r=await middlewares_1.HttpRequester.database.request(o,e,a,{},{cloudConfig:this.#t});if(!r.succeed)throw errors_1.errors.CALL_DATABASE_ERR(r);return r.data}async deleteCollection(t){const s="DELETE",o=this.#e(t),e=await middlewares_1.HttpRequester.database.request(s,o,{},{},{cloudConfig:this.#t});if(!e.succeed)throw errors_1.errors.CALL_DATABASE_ERR(e);return e.data}}exports.Database=Database; |
@@ -12,2 +12,3 @@ import { HttpRequestFailedResult } from './types'; | ||
export declare class FunctionError extends Error { | ||
httpStatus: number; | ||
code: ErrorCode; | ||
@@ -14,0 +15,0 @@ requestId: string; |
@@ -1,1 +0,1 @@ | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.errors=exports.FunctionError=exports.ErrorCode=void 0;const node_util_1=require("node:util");var ErrorCode;(function(e){e.INVALID_PARAM="INVALID_PARAM",e.CALL_FUNCTION_ERR="CALL_FUNCTION_ERR",e.CALL_STORAGE_ERR="CALL_STORAGE_ERR",e.CALL_DATABASE_ERR="CALL_DATABASE_ERR",e.CALL_OPENAPI_ERR="CALL_OPENAPI_ERR",e.SYS_ERR="SYS_ERR",e.NOT_FOUND="NOT_FOUND"})(ErrorCode=exports.ErrorCode||(exports.ErrorCode={}));class FunctionError extends Error{code;requestId;errCode=-1;get requestID(){return this.requestId}get errMsg(){return this.message}static create(t,r,...R){const A=new FunctionError((0,node_util_1.format)(r,...R));return A.code=t,A}static createByHttpRequestFailedResult(t,r){const R=FunctionError.create(t,`requestId ${r.requestId}, ${r.errMsg}`);return R.requestId=r.requestId,R.errCode=r.errCode,R}}exports.FunctionError=FunctionError,exports.errors={INVALID_PARAM(e,t){return FunctionError.create(ErrorCode.INVALID_PARAM,`Invalid param "${e}", ${t}`)},CALL_FUNCTION_ERR(e){return FunctionError.createByHttpRequestFailedResult(ErrorCode.CALL_FUNCTION_ERR,e)},CALL_STORAGE_ERR(e){return FunctionError.createByHttpRequestFailedResult(ErrorCode.CALL_STORAGE_ERR,e)},CALL_OPENAPI_ERR(e){return FunctionError.createByHttpRequestFailedResult(ErrorCode.CALL_OPENAPI_ERR,e)},INVALID_OPENAPI_RESPONSE_ERR(e,t){const r=FunctionError.create(ErrorCode.CALL_OPENAPI_ERR,`Invalid response ${JSON.stringify(t)}`);return r.requestId=e,r.errCode=-1,r},CALL_DATABASE_ERR(e){return FunctionError.createByHttpRequestFailedResult(ErrorCode.CALL_DATABASE_ERR,e)},SYS_ERR(e="\u5185\u90E8\u7CFB\u7EDF\u9519\u8BEF"){return FunctionError.create(ErrorCode.SYS_ERR,e)},NOT_FOUND(e){return FunctionError.create(ErrorCode.NOT_FOUND,e)}}; | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.errors=exports.FunctionError=exports.ErrorCode=void 0;const node_util_1=require("node:util");var ErrorCode;(function(e){e.INVALID_PARAM="INVALID_PARAM",e.CALL_FUNCTION_ERR="CALL_FUNCTION_ERR",e.CALL_STORAGE_ERR="CALL_STORAGE_ERR",e.CALL_DATABASE_ERR="CALL_DATABASE_ERR",e.CALL_OPENAPI_ERR="CALL_OPENAPI_ERR",e.SYS_ERR="SYS_ERR",e.NOT_FOUND="NOT_FOUND"})(ErrorCode=exports.ErrorCode||(exports.ErrorCode={}));class FunctionError extends Error{httpStatus;code;requestId;errCode=-1;get requestID(){return this.requestId}get errMsg(){return this.message}static create(r,t,...R){const A=new FunctionError((0,node_util_1.format)(t,...R));return A.code=r,A}static createByHttpRequestFailedResult(r,t){const R=FunctionError.create(r,`requestId ${t.requestId}, ${t.errMsg}`);return R.requestId=t.requestId,R.errCode=t.errCode,R.httpStatus=t.status,R}}exports.FunctionError=FunctionError,exports.errors={INVALID_PARAM(e,r){return FunctionError.create(ErrorCode.INVALID_PARAM,`Invalid param "${e}", ${r}`)},CALL_FUNCTION_ERR(e){return FunctionError.createByHttpRequestFailedResult(ErrorCode.CALL_FUNCTION_ERR,e)},CALL_STORAGE_ERR(e){return FunctionError.createByHttpRequestFailedResult(ErrorCode.CALL_STORAGE_ERR,e)},CALL_OPENAPI_ERR(e){return FunctionError.createByHttpRequestFailedResult(ErrorCode.CALL_OPENAPI_ERR,e)},INVALID_OPENAPI_RESPONSE_ERR(e,r){const t=FunctionError.create(ErrorCode.CALL_OPENAPI_ERR,`Invalid response ${JSON.stringify(r)}`);return t.requestId=e,t.errCode=-1,t},CALL_DATABASE_ERR(e){return FunctionError.createByHttpRequestFailedResult(ErrorCode.CALL_DATABASE_ERR,e)},SYS_ERR(e="\u5185\u90E8\u7CFB\u7EDF\u9519\u8BEF"){return FunctionError.create(ErrorCode.SYS_ERR,e)},NOT_FOUND(e){return FunctionError.create(ErrorCode.NOT_FOUND,e)}}; |
@@ -8,3 +8,3 @@ import { Cloud } from './Cloud'; | ||
export declare const callFunction: <T = any>(param: import("./types").CallFunctionParam) => Promise<import("./types").CallFunctionResult<T>>; | ||
export declare const database: (config?: import("./types").GetDatabaseOptions | undefined) => import("./Database/index").Database; | ||
export declare const database: (config?: import("./types").GetDatabaseOptions | undefined) => import("./Database").Database; | ||
export declare const mysql: () => import("./MySQL").MySQL; | ||
@@ -11,0 +11,0 @@ export declare const openapi: import("./Openapi").OpenapiFunction; |
@@ -5,3 +5,3 @@ import type { CloudConfig } from '@alipay/faas-server-utils'; | ||
constructor(config: CloudConfig, version: string); | ||
request(name: string, options?: Record<string, unknown>): Promise<any>; | ||
request(name: string, params?: Record<string, unknown>): Promise<any>; | ||
} |
@@ -1,1 +0,1 @@ | ||
"use strict";var __importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.OpenapiCaller=void 0;const snakecase_keys_1=__importDefault(require("snakecase-keys")),errors_1=require("../errors"),middlewares_1=require("../requester/middlewares");class OpenapiCaller{#e;#t;constructor(s,n){this.#e=s,this.#t=n}async request(s,n){const o="POST",a=this.#r(),t=(0,snakecase_keys_1.default)(Object.assign({},n),{deep:!0});t.biz_content&&typeof t.biz_content!="string"&&(t.biz_content=JSON.stringify(t.biz_content));const r=await middlewares_1.HttpRequester.openapi.request(o,a,t,{"x-openapi":s,"x-openapi-version":this.#t},{cloudConfig:this.#e});if(!r.succeed)throw errors_1.errors.CALL_OPENAPI_ERR(r);const c=`${s.replace(/\./g,"_")}_response`,i=r.data?.[c];if(!i)throw errors_1.errors.INVALID_OPENAPI_RESPONSE_ERR(r.requestId,r.data||"");return i}#r(){return`${this.#e.functionGatewayEndpoint}/functions/invokeOpenapi`}}exports.OpenapiCaller=OpenapiCaller; | ||
"use strict";var __importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.OpenapiCaller=void 0;const snakecase_keys_1=__importDefault(require("snakecase-keys")),errors_1=require("../errors"),middlewares_1=require("../requester/middlewares");class OpenapiCaller{#e;#t;constructor(r,n){this.#e=r,this.#t=n}async request(r,n){const o="POST",a=this.#s(),t=(0,snakecase_keys_1.default)(Object.assign({},n),{deep:!0});t.biz_content&&typeof t.biz_content!="string"&&(t.biz_content=JSON.stringify(t.biz_content));const c={"x-openapi":r,"x-openapi-version":this.#t},u={cloudConfig:this.#e},s=await middlewares_1.HttpRequester.openapi.request(o,a,t,c,u);if(s.succeed===!1)throw errors_1.errors.CALL_OPENAPI_ERR(s);const p=`${r.replace(/\./g,"_")}_response`,i=s.data?.[p];if(!i)throw errors_1.errors.INVALID_OPENAPI_RESPONSE_ERR(s.requestId,s.data||"");return i}#s(){return`${this.#e.functionGatewayEndpoint}/functions/invokeOpenapi`}}exports.OpenapiCaller=OpenapiCaller; |
import type { CloudConfig } from '@alipay/faas-server-utils'; | ||
import type { OpenapiConfig } from '../types'; | ||
import type { Openapi } from '../types/openapi/api'; | ||
import { OpenapiCaller } from './caller'; | ||
export type OpenapiFunction = Openapi & { | ||
(config?: OpenapiConfig): Openapi; | ||
}; | ||
export declare function createOpenapiCaller(config: CloudConfig, version?: string): OpenapiCaller; | ||
export declare function createOpenapi(config: CloudConfig): OpenapiFunction; |
@@ -1,1 +0,1 @@ | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.createOpenapi=void 0;const constant_1=require("../constant"),errors_1=require("../errors"),caller_1=require("./caller"),whitelist_1=require("./whitelist"),createOpenapiProxy=(e,n)=>new Proxy(e,{get(o,r){const t=whitelist_1.OPENAPI_WHITELIST[r];if(!t)throw errors_1.errors.NOT_FOUND(`openapi ${r} is not supported`);return{request:s=>n.request(t,s)}}});function createOpenapi(e){const n=new caller_1.OpenapiCaller(e,constant_1.OPENAPI_VERSION);function o(r){const t=new caller_1.OpenapiCaller(e,r?.version||constant_1.OPENAPI_VERSION);return createOpenapiProxy({},t)}return createOpenapiProxy(o,n)}exports.createOpenapi=createOpenapi; | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.createOpenapi=exports.createOpenapiCaller=void 0;const constant_1=require("../constant"),errors_1=require("../errors"),caller_1=require("./caller"),whitelist_1=require("./whitelist");function createOpenapiCaller(e,r){return new caller_1.OpenapiCaller(e,r||constant_1.OPENAPI_VERSION)}exports.createOpenapiCaller=createOpenapiCaller;const createOpenapiProxy=(e,r)=>new Proxy(e,{get(a,t){const n=whitelist_1.OPENAPI_WHITELIST[t];if(!n)throw errors_1.errors.NOT_FOUND(`openapi ${t} is not supported`);return{request:o=>r.request(n,o)}}});function createOpenapi(e){const r=createOpenapiCaller(e);function a(t){const n=createOpenapiCaller(e,t?.version);return createOpenapiProxy({},n)}return createOpenapiProxy(a,r)}exports.createOpenapi=createOpenapi; |
@@ -1,1 +0,1 @@ | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.callDatabaseMiddleware=void 0;async function callDatabaseMiddleware(e,t){await t();const s=e.requestId;if(e.res.status!==200){const{code:a,message:r}=e.res.data;e.result={succeed:!1,status:e.res.status,requestId:s,errCode:a,errMsg:`code = ${a}, msg = ${r}`}}else e.result={succeed:!0,status:e.res.status,requestId:s,data:e.res.data.data}}exports.callDatabaseMiddleware=callDatabaseMiddleware; | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.callDatabaseMiddleware=void 0;async function callDatabaseMiddleware(e,t){await t();const s=e.requestId;if(e.res.status!==200){const{code:a,message:r}=e.res.data||{code:-1,message:"unknown"};e.result={succeed:!1,status:e.res.status,requestId:s,errCode:a,errMsg:`code = ${a}, msg = ${r}`}}else e.result={succeed:!0,status:e.res.status,requestId:s,data:e.res.data.data}}exports.callDatabaseMiddleware=callDatabaseMiddleware; |
@@ -1,1 +0,1 @@ | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.callFunctionMiddleware=void 0;async function callFunctionMiddleware(e,t){await t();const s=e.requestId;if(e.res.status!==200){const r=e.res.data;e.result={succeed:!1,status:e.res.status,requestId:s,errCode:-1,errMsg:`code = ${r.errCode}, msg = ${r.errMsg}`}}else e.result={succeed:!0,status:e.res.status,requestId:s,data:e.res.data}}exports.callFunctionMiddleware=callFunctionMiddleware; | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.callFunctionMiddleware=void 0;async function callFunctionMiddleware(e,a){e.req.requestOptions.headers["x-alipay-cloud-mode"]="function",await a();const t=e.requestId;if(e.res.status!==200){const s=e.res.data;let r="";s?(r=`code = ${s.errCode}, msg = ${s.errMsg}`,s.errDetail&&(r+=`, detail = ${s.errDetail}`)):r=`unknown error, status: ${e.res.status}`,e.result={succeed:!1,status:e.res.status,requestId:t,errCode:-1,errMsg:r}}else e.result={succeed:!0,status:e.res.status,requestId:t,data:e.res.data}}exports.callFunctionMiddleware=callFunctionMiddleware; |
@@ -1,1 +0,1 @@ | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.callOpenapiMiddleware=void 0;async function callOpenapiMiddleware(e,a){await a();const s=e.requestId;if(e.res.status!==200){const{code:r,message:t}=e.res.data;e.result={succeed:!1,status:e.res.status,requestId:s,errCode:-1,errMsg:`code = ${r}, msg = ${t}`}}else e.result={succeed:!0,status:e.res.status,requestId:s,data:e.res.data}}exports.callOpenapiMiddleware=callOpenapiMiddleware; | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.callOpenapiMiddleware=void 0;async function callOpenapiMiddleware(e,a){await a();const s=e.requestId;if(e.res.status!==200){const{code:r,message:t}=e.res.data||{code:-1,message:"unknown"};e.result={succeed:!1,status:e.res.status,requestId:s,errCode:-1,errMsg:`code = ${r}, msg = ${t}`}}else e.result={succeed:!0,status:e.res.status,requestId:s,data:e.res.data}}exports.callOpenapiMiddleware=callOpenapiMiddleware; |
@@ -1,1 +0,1 @@ | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.callStorageMiddleware=void 0;async function callStorageMiddleware(e,r){await r();const s=e.requestId;if(e.res.status!==200){const{code:a,message:t}=e.res.data;e.result={succeed:!1,status:e.res.status,requestId:s,errCode:a,errMsg:`code = ${a}, msg = ${t}`}}else e.result={succeed:!0,status:e.res.status,requestId:s,data:e.res.data.data}}exports.callStorageMiddleware=callStorageMiddleware; | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.callStorageMiddleware=void 0;async function callStorageMiddleware(e,r){await r();const s=e.requestId;if(e.res.status!==200){const{code:a,message:t}=e.res.data||{code:-1,message:"unknown"};e.result={succeed:!1,status:e.res.status,requestId:s,errCode:a,errMsg:`code = ${a}, msg = ${t}`}}else e.result={succeed:!0,status:e.res.status,requestId:s,data:e.res.data.data}}exports.callStorageMiddleware=callStorageMiddleware; |
@@ -1,1 +0,1 @@ | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.errorHandlerMiddleware=void 0;const node_util_1=require("node:util"),debug=(0,node_util_1.debuglog)("faas-server-sdk:httpRequest");async function errorHandlerMiddleware(e,t){try{await t()}catch(r){debug("%s %o got failed: %s",e.req.requestOptions.method,e.req.url,r.stack),e.result={succeed:!1,errCode:-1,status:-1,errMsg:`code = -1, msg = ${r.toString()}`,requestId:e.requestId}}}exports.errorHandlerMiddleware=errorHandlerMiddleware; | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.errorHandlerMiddleware=void 0;const node_util_1=require("node:util"),debug=(0,node_util_1.debuglog)("faas-server-sdk:httpRequest");async function errorHandlerMiddleware(e,t){try{await t()}catch(r){if(debug("%s %o got failed: %s",e.req.requestOptions.method,e.req.url,r.stack),!e.req.convertRequestErrorToResult)throw r;e.result={succeed:!1,errCode:-1,status:-1,errMsg:`code = -1, msg = ${r.toString()}`,requestId:e.requestId}}}exports.errorHandlerMiddleware=errorHandlerMiddleware; |
@@ -10,2 +10,3 @@ /// <reference types="node" /> | ||
cloudConfig: CloudConfig; | ||
convertRequestErrorToResult?: boolean; | ||
}; | ||
@@ -15,3 +16,4 @@ export declare class HttpRequester { | ||
constructor(middlewares: Array<Middleware<HttpRequestContext<any, any>>>); | ||
request<T>(method: HttpMethod, url: string, data: any, headers: IncomingHttpHeaders, options: Options): Promise<HttpRequestResult<T>>; | ||
request<R>(method: HttpMethod, url: string, data: any, headers: IncomingHttpHeaders, options: Options): Promise<HttpRequestResult<R>>; | ||
requestRaw<T, R>(method: HttpMethod, url: string, data: any, headers: IncomingHttpHeaders, options: Options): Promise<HttpRequestContext<T, R>>; | ||
static get function(): HttpRequester; | ||
@@ -18,0 +20,0 @@ static get database(): HttpRequester; |
@@ -1,1 +0,1 @@ | ||
"use strict";var __importDefault=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.HttpRequester=void 0;const node_assert_1=__importDefault(require("node:assert")),node_crypto_1=require("node:crypto"),koa_compose_1=__importDefault(require("koa-compose")),call_openapi_middleware_1=require("./call_openapi_middleware"),HttpRequestContext_1=require("./HttpRequestContext"),call_database_middleware_1=require("./call_database_middleware"),call_function_middleware_1=require("./call_function_middleware"),call_middleware_1=require("./call_middleware"),sign_middleware_factory_1=require("./sign_middleware_factory"),init_call_dataproxy_headers_middleware_1=require("./init_call_dataproxy_headers_middleware"),error_handler_middleware_1=require("./error_handler_middleware");class HttpRequester{static#e;static#t;static#a;static#r;#i;constructor(e){this.#i=(0,koa_compose_1.default)(e)}async request(e,n,s,r,l){const a=l.cloudConfig;(0,node_assert_1.default)(a,"cloud config not set");const o=JSON.stringify(s),c=(0,node_crypto_1.randomUUID)();r["x-request-id"]=c;const i={method:e,contentType:"application/json",content:o,dataType:"json",headers:r};a.timeout!==void 0&&(i.timeout=a.timeout);const u={url:new URL(n),requestOptions:i},d=new HttpRequestContext_1.HttpRequestContext(u,a);return await this.#i(d),d.result}static get function(){if(!this.#e){const e=[error_handler_middleware_1.errorHandlerMiddleware,(0,sign_middleware_factory_1.signMiddlewareFactory)(["x-to-function-name"]),call_function_middleware_1.callFunctionMiddleware,call_middleware_1.callMiddleware];this.#e=new HttpRequester(e)}return this.#e}static get database(){if(!this.#t){const e=[error_handler_middleware_1.errorHandlerMiddleware,(0,init_call_dataproxy_headers_middleware_1.createInitCallDataProxyHeadersMiddleware)("mongo"),(0,sign_middleware_factory_1.signMiddlewareFactory)(["x-data-api-type","x-expire-timestamp"]),call_database_middleware_1.callDatabaseMiddleware,call_middleware_1.callMiddleware];this.#t=new HttpRequester(e)}return this.#t}static get storage(){if(!this.#a){const e=[error_handler_middleware_1.errorHandlerMiddleware,(0,init_call_dataproxy_headers_middleware_1.createInitCallDataProxyHeadersMiddleware)("oss"),(0,sign_middleware_factory_1.signMiddlewareFactory)(["x-data-api-type","x-expire-timestamp"]),call_database_middleware_1.callDatabaseMiddleware,call_middleware_1.callMiddleware];this.#a=new HttpRequester(e)}return this.#a}static get openapi(){if(!this.#r){const e=[error_handler_middleware_1.errorHandlerMiddleware,(0,sign_middleware_factory_1.signMiddlewareFactory)(["x-openapi","x-openapi-version"]),call_openapi_middleware_1.callOpenapiMiddleware,call_middleware_1.callMiddleware];this.#r=new HttpRequester(e)}return this.#r}}exports.HttpRequester=HttpRequester; | ||
"use strict";var __importDefault=this&&this.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.HttpRequester=void 0;const node_assert_1=__importDefault(require("node:assert")),node_crypto_1=require("node:crypto"),koa_compose_1=__importDefault(require("koa-compose")),faas_server_utils_1=require("@alipay/faas-server-utils"),call_openapi_middleware_1=require("./call_openapi_middleware"),HttpRequestContext_1=require("./HttpRequestContext"),call_database_middleware_1=require("./call_database_middleware"),call_storage_middleware_1=require("./call_storage_middleware"),call_function_middleware_1=require("./call_function_middleware"),call_middleware_1=require("./call_middleware"),sign_middleware_factory_1=require("./sign_middleware_factory"),init_call_dataproxy_headers_middleware_1=require("./init_call_dataproxy_headers_middleware"),error_handler_middleware_1=require("./error_handler_middleware"),constant_1=require("../../constant");class HttpRequester{static#e;static#t;static#r;static#a;#i;constructor(e){this.#i=(0,koa_compose_1.default)(e)}async request(e,s,n,t,r){return r.convertRequestErrorToResult=!0,(await this.requestRaw(e,s,n,t,r)).result}async requestRaw(e,s,n,t,r){const a=r.cloudConfig;(0,node_assert_1.default)(a,"cloud config not set");const u=JSON.stringify(n),o=(0,faas_server_utils_1.getAlipayContext)();t["x-alipay-callid"]=t["x-request-id"]=o.TRACEID||(0,node_crypto_1.randomUUID)();let l=process.env.RUNTIME_CURRENT_SOURCE||"alipay_unknown";process.env.RUNTIME_FUNCTION_NAME&&(l=`${l}:${o.ENV}:${process.env.RUNTIME_FUNCTION_NAME}`);const _=o.SOURCE||"alipay_unknown";t["x-alipay-source"]=`${_},${l}`,t["user-agent"]=constant_1.SDK_USER_AGENT;const d={method:e,contentType:"application/json",content:u,dataType:"json",headers:t};a.timeout!==void 0&&(d.timeout=a.timeout);const w={url:new URL(s),requestOptions:d,convertRequestErrorToResult:!!r.convertRequestErrorToResult},c=new HttpRequestContext_1.HttpRequestContext(w,a);return await this.#i(c),c}static get function(){if(!this.#e){const e=[error_handler_middleware_1.errorHandlerMiddleware,(0,sign_middleware_factory_1.signMiddlewareFactory)(["x-to-function-name"]),call_function_middleware_1.callFunctionMiddleware,call_middleware_1.callMiddleware];this.#e=new HttpRequester(e)}return this.#e}static get database(){if(!this.#t){const e=[error_handler_middleware_1.errorHandlerMiddleware,(0,init_call_dataproxy_headers_middleware_1.createInitCallDataProxyHeadersMiddleware)("mongo"),(0,sign_middleware_factory_1.signMiddlewareFactory)(["x-data-api-type","x-expire-timestamp"]),call_database_middleware_1.callDatabaseMiddleware,call_middleware_1.callMiddleware];this.#t=new HttpRequester(e)}return this.#t}static get storage(){if(!this.#r){const e=[error_handler_middleware_1.errorHandlerMiddleware,(0,init_call_dataproxy_headers_middleware_1.createInitCallDataProxyHeadersMiddleware)("oss"),(0,sign_middleware_factory_1.signMiddlewareFactory)(["x-data-api-type","x-expire-timestamp"]),call_storage_middleware_1.callStorageMiddleware,call_middleware_1.callMiddleware];this.#r=new HttpRequester(e)}return this.#r}static get openapi(){if(!this.#a){const e=[error_handler_middleware_1.errorHandlerMiddleware,(0,sign_middleware_factory_1.signMiddlewareFactory)(["x-openapi","x-openapi-version"]),call_openapi_middleware_1.callOpenapiMiddleware,call_middleware_1.callMiddleware];this.#a=new HttpRequester(e)}return this.#a}}exports.HttpRequester=HttpRequester; |
@@ -1,1 +0,1 @@ | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.createInitCallDataProxyHeadersMiddleware=void 0;function createInitCallDataProxyHeadersMiddleware(a){return async function(e,r){e.req.requestOptions.headers["x-data-api-type"]=a,e.req.requestOptions.headers["x-expire-timestamp"]=`${Date.now()+6e4}`,await r()}}exports.createInitCallDataProxyHeadersMiddleware=createInitCallDataProxyHeadersMiddleware; | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.createInitCallDataProxyHeadersMiddleware=void 0;function createInitCallDataProxyHeadersMiddleware(a){return async function(e,r){e.req.requestOptions.headers["x-alipay-cloud-mode"]=a,e.req.requestOptions.headers["x-data-api-type"]=a,e.req.requestOptions.headers["x-expire-timestamp"]=`${Date.now()+6e4}`,await r()}}exports.createInitCallDataProxyHeadersMiddleware=createInitCallDataProxyHeadersMiddleware; |
@@ -0,1 +1,4 @@ | ||
/// <reference types="node" /> | ||
import type { IncomingHttpHeaders } from 'node:http'; | ||
import type { HttpMethod } from 'urllib'; | ||
import type { CloudConfig } from '@alipay/faas-server-utils'; | ||
@@ -6,2 +9,3 @@ import type { UploadFileParam, UploadFileResult, DownloadFileParam, DownloadFileResult, DeleteFileResult, GetTempFileURLResult } from '../types'; | ||
constructor(config: CloudConfig); | ||
requestRaw(method: HttpMethod, urlpath: string, data: object, headers: IncomingHttpHeaders): Promise<import("urllib").HttpClientResponse<unknown>>; | ||
uploadFile(param: UploadFileParam): Promise<UploadFileResult>; | ||
@@ -8,0 +12,0 @@ downloadFile(param: DownloadFileParam): Promise<DownloadFileResult>; |
@@ -1,1 +0,1 @@ | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Storage=void 0;const node_util_1=require("node:util"),urllib_1=require("urllib"),errors_1=require("../errors"),middlewares_1=require("../requester/middlewares"),debug=(0,node_util_1.debuglog)("faas-server-sdk:Storage");class Storage{#t;constructor(t){this.#t=t}#o(t){return`${this.#t.functionStorageEndpoint}/${t}?upload_url`}#i(t){return`${this.#t.functionStorageEndpoint}/${t}?download_url&expire=3600`}#n(){return`${this.#t.functionStorageEndpoint}/?delete`}#a(){return`${this.#t.functionStorageEndpoint}/?download_url`}#u(t){if(typeof t!="string")return"must be a string";if(t=t.trim(),!t)return"cannot be an empty string";if(t.startsWith("/"))return"cannot start with /";if(t.includes("//"))return"cannot appear consecutively /";if(t.length>850)return"maximum encoding length of 850 bytes"}#e(t){if(typeof t!="string")return"must be a string";if(t=t.trim(),!t)return"cannot be an empty string"}#r(t){return`cloud://${this.#t.toEnvId}/${t.replace(/^\/+/,"")}`}#s(t){const s=t.trim().replace(/^cloud:\/\//,""),n=s.indexOf("/");if(n<=0)throw errors_1.errors.INVALID_PARAM("fileID","is invalid");const r=s.substring(0,n),e=s.substring(n+1);return r!==this.#t.toEnvId&&console.warn(`file ${t} does not belong to env ${this.#t.toEnvId}`),e}async uploadFile(t){const s=this.#u(t.cloudPath);if(s)throw errors_1.errors.INVALID_PARAM("cloudPath",s);const n=this.#o(t.cloudPath.trim()),r=await middlewares_1.HttpRequester.storage.request("GET",n,"",{},{cloudConfig:this.#t});if(!r.succeed)throw errors_1.errors.CALL_STORAGE_ERR(r);const e=this.#r(r.data.file_id);let i=r.data.upload_url;process.env.NODE_ENV==="test"&&(i=i.replace("https://","http://"));let o,u;Buffer.isBuffer(t.fileContent)?u=t.fileContent:o=t.fileContent;const a=await(0,urllib_1.request)(i,{method:"PUT",content:u,stream:o,timeout:6e4});if(debug("uploadFile fileID: %o, uploadURL: %o got response status: %o, headers: %o, body: %o",e,i,a.status,a.headers,a.data.toString()),a.status!==200)throw errors_1.errors.CALL_STORAGE_ERR({succeed:!1,errMsg:"upload file to storage error",errCode:-1,requestId:r.requestId,status:a.status});return{fileID:e,statusCode:a.status}}async downloadFile(t){const s=this.#e(t.fileID);if(s)throw errors_1.errors.INVALID_PARAM("fileID",s);const n=this.#s(t.fileID),r=this.#i(n),e=await middlewares_1.HttpRequester.storage.request("GET",r,"",{},{cloudConfig:this.#t});if(!e.succeed)throw errors_1.errors.CALL_STORAGE_ERR(e);const i=e.data.download_url,o=await(0,urllib_1.request)(i,{timeout:6e4});if(debug("downloadFile fileID: %o, downloadURL: %o got response status: %o, headers: %o, body length: %o",t.fileID,i,o.status,o.headers,o.data.length),o.status!==200)throw errors_1.errors.CALL_STORAGE_ERR({succeed:!1,errMsg:"download file from storage error",errCode:-1,requestId:e.requestId,status:o.status});return{fileContent:o.data,statusCode:o.status}}async deleteFile(t){if(!Array.isArray(t)||t.length===0)throw errors_1.errors.INVALID_PARAM("fileList","cannot be an empty list");const s=[];for(const e of t){const i=this.#e(e);if(i)throw errors_1.errors.INVALID_PARAM("fileID",i);const o=this.#s(e);s.push(o)}const n=this.#n(),r=await middlewares_1.HttpRequester.storage.request("POST",n,{file_list:s},{},{cloudConfig:this.#t});if(!r.succeed)throw errors_1.errors.CALL_STORAGE_ERR(r);return{fileList:r.data.file_list.map(e=>({fileID:this.#r(e.file_id),status:e.status?0:-1,errMsg:e.status?"ok":e.result_message}))}}async getTempFileURL(t){if(!Array.isArray(t)||t.length===0)throw errors_1.errors.INVALID_PARAM("fileList","cannot be an empty list");if(t.length>50)throw errors_1.errors.INVALID_PARAM("fileList","Maximum 50 files");const s=[];for(const e of t){const i=this.#e(e);if(i)throw errors_1.errors.INVALID_PARAM("fileID",i);const o=this.#s(e);s.push({file_id:o,expire:600})}const n=this.#a(),r=await middlewares_1.HttpRequester.storage.request("POST",n,{file_list:s},{},{cloudConfig:this.#t});if(!r.succeed)throw errors_1.errors.CALL_STORAGE_ERR(r);return{fileList:r.data.file_list.map(e=>({fileID:this.#r(e.file_id),tempFileURL:e.download_url,status:e.status?0:-1,errMsg:e.status?"ok":e.result_message}))}}}exports.Storage=Storage; | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Storage=void 0;const node_util_1=require("node:util"),urllib_1=require("urllib"),errors_1=require("../errors"),middlewares_1=require("../requester/middlewares"),debug=(0,node_util_1.debuglog)("faas-server-sdk:Storage");class Storage{#t;constructor(t){this.#t=t}async requestRaw(t,s,o,r){const e=`${this.#t.functionStorageEndpoint}${s}`,{res:n}=await middlewares_1.HttpRequester.storage.requestRaw(t,e,o,r,{cloudConfig:this.#t});return n}#o(t){return`${this.#t.functionStorageEndpoint}/${t}?upload_url`}#n(t){return`${this.#t.functionStorageEndpoint}/${t}?download_url&expire=3600`}#i(){return`${this.#t.functionStorageEndpoint}/?delete`}#a(){return`${this.#t.functionStorageEndpoint}/?download_url`}#u(t){if(typeof t!="string")return"must be a string";if(t=t.trim(),!t)return"cannot be an empty string";if(t.startsWith("/"))return"cannot start with /";if(t.includes("//"))return"cannot appear consecutively /";if(t.length>850)return"maximum encoding length of 850 bytes"}#e(t){if(typeof t!="string")return"must be a string";if(t=t.trim(),!t)return"cannot be an empty string"}#r(t){return`cloud://${this.#t.toEnvId}/${t.replace(/^\/+/,"")}`}#s(t){const s=t.trim().replace(/^cloud:\/\//,""),o=s.indexOf("/");if(o<=0)throw errors_1.errors.INVALID_PARAM("fileID","is invalid");const r=s.substring(0,o),e=s.substring(o+1);return r!==this.#t.toEnvId&&console.warn(`file ${t} does not belong to env ${this.#t.toEnvId}`),e}async#l(t){const s=this.#u(t);if(s)throw errors_1.errors.INVALID_PARAM("cloudPath",s);const o=this.#o(t.trim()),r=await middlewares_1.HttpRequester.storage.request("GET",o,"",{},{cloudConfig:this.#t});if(!r.succeed)throw errors_1.errors.CALL_STORAGE_ERR(r);const e=this.#r(r.data.file_id),n=r.data.upload_url;return{fileID:e,url:n,requestID:r.requestId}}async uploadFile(t){const{fileID:s,url:o,requestID:r}=await this.#l(t.cloudPath);let e,n;Buffer.isBuffer(t.fileContent)?n=t.fileContent:e=t.fileContent;const i=await(0,urllib_1.request)(o,{method:"PUT",content:n,stream:e,timeout:6e4});if(debug("uploadFile fileID: %o, uploadURL: %o got response status: %o, headers: %o, body: %o",s,o,i.status,i.headers,i.data.toString()),i.status!==200)throw errors_1.errors.CALL_STORAGE_ERR({succeed:!1,errMsg:"upload file to storage error",errCode:-1,requestId:r,status:i.status});return{fileID:s,statusCode:i.status}}async#d(t){const s=this.#e(t);if(s)throw errors_1.errors.INVALID_PARAM("fileID",s);const o=this.#s(t),r=this.#n(o),e=await middlewares_1.HttpRequester.storage.request("GET",r,"",{},{cloudConfig:this.#t});if(!e.succeed)throw errors_1.errors.CALL_STORAGE_ERR(e);return{url:e.data.download_url,requestID:e.requestId}}async downloadFile(t){const{url:s,requestID:o}=await this.#d(t.fileID),r=await(0,urllib_1.request)(s,{timeout:6e4});if(debug("downloadFile fileID: %o, downloadURL: %o got response status: %o, headers: %o, body length: %o",t.fileID,s,r.status,r.headers,r.data.length),r.status!==200)throw errors_1.errors.CALL_STORAGE_ERR({succeed:!1,errMsg:"download file from storage error",errCode:-1,requestId:o,status:r.status});return{fileContent:r.data,statusCode:r.status}}async deleteFile(t){if(!Array.isArray(t)||t.length===0)throw errors_1.errors.INVALID_PARAM("fileList","cannot be an empty list");const s=[];for(const e of t){const n=this.#e(e);if(n)throw errors_1.errors.INVALID_PARAM("fileID",n);const i=this.#s(e);s.push(i)}const o=this.#i(),r=await middlewares_1.HttpRequester.storage.request("POST",o,{file_list:s},{},{cloudConfig:this.#t});if(!r.succeed)throw errors_1.errors.CALL_STORAGE_ERR(r);return{fileList:r.data.file_list.map(e=>({fileID:this.#r(e.file_id),status:e.status?0:-1,errMsg:e.status?"ok":e.result_message}))}}async getTempFileURL(t){if(!Array.isArray(t)||t.length===0)throw errors_1.errors.INVALID_PARAM("fileList","cannot be an empty list");if(t.length>50)throw errors_1.errors.INVALID_PARAM("fileList","Maximum 50 files");const s=[];for(const e of t){const n=this.#e(e);if(n)throw errors_1.errors.INVALID_PARAM("fileID",n);const i=this.#s(e);s.push({file_id:i,expire:600})}const o=this.#a(),r=await middlewares_1.HttpRequester.storage.request("POST",o,{file_list:s},{},{cloudConfig:this.#t});if(!r.succeed)throw errors_1.errors.CALL_STORAGE_ERR(r);return{fileList:r.data.file_list.map(e=>({fileID:this.#r(e.file_id),tempFileURL:e.download_url,status:e.status?0:-1,errMsg:e.status?"ok":e.result_message}))}}}exports.Storage=Storage; |
@@ -38,2 +38,3 @@ /// <reference types="node" /> | ||
errMsg: string; | ||
errDetail?: string; | ||
} | ||
@@ -63,2 +64,3 @@ export interface CallDatabaseResponse<T = object> { | ||
requestOptions: RequestOptions; | ||
convertRequestErrorToResult: boolean; | ||
} | ||
@@ -65,0 +67,0 @@ export interface HttpRequestBaseResult { |
{ | ||
"name": "@alipay/faas-server-sdk", | ||
"version": "1.0.10", | ||
"version": "1.1.0-alpha.0", | ||
"description": "云函数服务 SDK", | ||
@@ -11,3 +11,6 @@ "main": "lib/index.js", | ||
"lint": "eslint src test --cache --fix --ext ts", | ||
"build": "tsc -p ./tsconfig.json && minimize-js lib", | ||
"prebuild": "npm run clean", | ||
"build": "tsc -p ./tsconfig.json", | ||
"postbuild": "npm run minimize", | ||
"minimize": "minimize-js lib", | ||
"clean": "tsc --build --clean", | ||
@@ -17,3 +20,3 @@ "test": "egg-bin test", | ||
"ci": "npm run cov && npm run build", | ||
"prepublishOnly": "npm run clean && npm run build" | ||
"prepublishOnly": "npm run build" | ||
}, | ||
@@ -26,3 +29,3 @@ "license": "MIT", | ||
"@types/mocha": "^10.0.1", | ||
"@types/node": "^18.11.18", | ||
"@types/node": "^20.1.3", | ||
"egg-bin": "^6.1.2", | ||
@@ -33,7 +36,7 @@ "eslint": "^8.34.0", | ||
"mm": "^3.2.1", | ||
"typescript": "^4.9.4" | ||
"typescript": "^5.0.4" | ||
}, | ||
"dependencies": { | ||
"@alipay/faas-db-builder": "^1.0.10", | ||
"@alipay/faas-server-utils": "^1.0.10", | ||
"@alipay/faas-db-builder": "^1.1.0-alpha.0", | ||
"@alipay/faas-server-utils": "^1.1.0-alpha.0", | ||
"ali-rds": "^5.1.2", | ||
@@ -40,0 +43,0 @@ "koa-compose": "^4.1.0", |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 1 instance in 1 package
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 1 instance in 1 package
No v1
QualityPackage is not semver >=1. This means it is not stable and does not support ^ ranges.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 1 instance in 1 package
265793
5314
20
20