{"id":24011921,"url":"https://github.com/paraself/leancloud-cloud-decorator","last_synced_at":"2025-04-15T06:51:41.595Z","repository":{"id":34891182,"uuid":"187434918","full_name":"paraself/leancloud-cloud-decorator","owner":"paraself","description":"适用于LeanCloud的云函数装饰器，支持缓存、schema校验、权限检查、客户端API发布等功能","archived":false,"fork":false,"pushed_at":"2022-12-06T16:00:41.000Z","size":758,"stargazers_count":8,"open_issues_count":10,"forks_count":0,"subscribers_count":5,"default_branch":"master","last_synced_at":"2025-03-28T17:21:18.670Z","etag":null,"topics":["decorator","leancloud","ts","typescript"],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/paraself.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2019-05-19T04:45:41.000Z","updated_at":"2024-05-21T05:34:19.000Z","dependencies_parsed_at":"2023-01-15T09:59:13.923Z","dependency_job_id":null,"html_url":"https://github.com/paraself/leancloud-cloud-decorator","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/paraself%2Fleancloud-cloud-decorator","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/paraself%2Fleancloud-cloud-decorator/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/paraself%2Fleancloud-cloud-decorator/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/paraself%2Fleancloud-cloud-decorator/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/paraself","download_url":"https://codeload.github.com/paraself/leancloud-cloud-decorator/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248654031,"owners_count":21140236,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["decorator","leancloud","ts","typescript"],"created_at":"2025-01-08T05:42:47.331Z","updated_at":"2025-04-15T06:51:41.575Z","avatar_url":"https://github.com/paraself.png","language":"TypeScript","readme":"# leancloud cloud decorator\n通过装饰器自动加函数加入到leancloud的云函数定义中, 并加入缓存, 权限验证, 参数验证, 自动生成前端接口sdk等功能。\n\n**注意：装饰器必须在TS环境中使用, 如果你不知道如何在LC中配置TS环境，请看[LC云引擎TS示例项目](https://github.com/paraself/leancloud-node-ts)**\n\n## 安装方法\n```shell\n$ npm install leancloud-cloud-decorator\n```\n\n## 初始化\n```typescript\nimport { init } from 'leancloud-cloud-decorator'\ninit({\n   // redis地址\n  redisUrl: 'your redis url',\n   // redis保存前缀\n  redisPrefix: 'prefax',\n  //错误回调,可选参数,用于搜集错误\n  errorCallback:errorInfo =\u003e {\n    console.error(errorInfo)\n    return errorInfo.error\n  },\n  //云函数被调用回调,可选参数,用于搜集云函数调用信息\n  cloudInvokeCallback:(name, request) =\u003e {\n    console.log(request.expressReq)\n  }\n})\n```\n\n## 定义云函数\n\n这里我们约定，所有的云函数文件，必须放在``src/cloud/xxxx.ts``里。一般一个ts文件，是一个云函数命名空间。例如``user.ts``, ``payment.ts``等。\n在每个云函数文件中，需要导出一个云函数模块的实例，写法如下：\n\n```typescript\n// 云引擎部分：src/cloud/user.ts 将用户相关的云函数定义写在这个文件里\nimport { Cloud, CloudParams } from 'leancloud-cloud-decorator'\n\nclass User {\n    \n    /**\n    * 获取用户自身信息, 会自动注册名字为User.GetUserInfo 的云函数\n    */\n    @Cloud()\n    async GetUserInfo(params:CloudParams) : Promise\u003cany\u003e{\n        // 直接返回内置字段 currentUser ,当前用户信息. 默认只有登入的用户才能调用此云函数\n        return params.currentUser\n    }\n\n}\nlet user = new User()\nexport default user\n\n// 项目入口：src/app.ts 在这里记得导入一次上面的模块, 即可加载上面的定义为实际的云函数\nimport './cloud/user.ts'\n\n```\n这样实际上是定义了一个名字叫做 ``User.GetUserInfo``的云函数。直接在客户端可以用LC的``AC.Cloud.run``方法来直接调用云函数。除了LC的这种方法之外，我们也可以从后端自动发布前端的接口api模块给前端用。这样做的好处是，接口参数，类型等信息，直接集成在api模块里了。这个我们后面会讲到。\n```typescript\n//客户端部分\n// 1. LC的云函数调用方法\nAV.Cloud.run('User.GetUserInfo').then(r=\u003econsole.log(r))\n// 2. 如果使用了本装饰器的云函数前端api发布功能，则可以在前端这么使用\nlet user = await User.GetUserInfo(xxxx)\n```\n\n## 云函数参数\n通过TS里的interface，我们可以在前后端统一参数的类型。后端定义接口的参数类型，这个类型能够随着api发布，发布到前端进行静态的类型检查，避免前后端经常对于接口参数不明确的问题。\n```typescript\n// 云引擎部分\nimport { Cloud, CloudParams } from 'leancloud-cloud-decorator'\nimport Joi from 'joi'\n\n// 云函数参数接口必须继承CloudParams\ninterface GetUserInfoByIdParams extends CloudParams{\n  userId: string\n  isAnonymous?: boolean // 可选参数\n}\n\nclass User {\n    /**\n    * 获取指定用户信息\n    */\n    @Cloud\u003cGetUserInfoByIdParams\u003e({\n        schema: {\n          //userId 只能为长度为24位的字符串,且为必填,不符合条件的参数会进程reject处理\n          userId: Joi.string().length(24).required(),\n          isAnonymous: Joi.boolean().optional()\n        }\n    })\n    async GetUserInfoById(params:GetUserInfoByIdParams) : Promise\u003cany\u003e{\n        // 直接返回内置字段 currentUser。默认所有的云函数都必须检验用户的信息，并拿到currentUser。如果你不需要currentUser的话，则可以设置：``noUser: true`` 进行关闭。\n        return params.currentUser\n    }\n}\n```\n\n## 缓存设置\n云函数设置里，加上cache字段，将会缓存云函数的返回内容，缓存期间请求云函数，不会真正执行云函数，会直接返回之前的缓存内容，直到缓存过期之后，请求云函数才会再次执行一次。\n\n```typescript\n//云引擎部分\nimport { Cloud, CloudParams } from 'leancloud-cloud-decorator'\n\n//云函数参数接口必须继承CloudParams\ninterface GetTimeParams extends CloudParams{\n  name?: string\n  id?: string\n}\nclass User {\n    //定义一个,每过一小时,刷新一次时间信息的云函数\n    @Cloud\u003c\u003e({\n        schema:{\n          //两个参数都为可选参数\n          name: Joi.string().optional(),\n          id: Joi.string().optional(),\n        }\n        cache: {\n            //参数有id字段,或者为'id','name' 字段组合时,才会使用缓存，只有name的话，不会开启缓存\n            params: [['id'],['id','name']],\n            //按小时缓存\n            timeUnit: 'hour'\n            //如果加上此设置,将会为每个用户单独创建一份缓存,适用于每个用户返回的内容不一样的场景\n            currentUser:true,\n            // 过期时间基于时间单位还是请求时间. 默认request. timeUnit为某个时间单位的整点开始即时,request为请求的时候开始计时\n            expireBy: 'request'\n        }\n    })\n    async GetTime() : Promise\u003cstring\u003e{\n        return new Date().toString()\n    }\n}\n\nlet user = new User()\nexport default user\n// 也可以后端代码的其他位置，直接import这个模块，调用里面的云函数\nuser.GetTime()\n```\n## 函数防抖\ndebounce字段为函数防抖动配置,配置内容为参数列表条件的数组.当用户参数满足云函数配置中的其中一个数组的条件时启用函数防抖\n同一个用户，同样的函数名，如果参数相同的话，前一个请求如果没有结束完，下一个请求就会被debounce\n```typescript\nclass Test{\n  @Cloud\u003cTestDebounceParams\u003e({\n    schema:{\n      expId:Joi.string().optional(),\n      id:Joi.string().optional(),\n    },\n    debounce:[[\"expId\"]]\n  })\n  async TestDebounce(params:TestDebounceParams){\n    await new Promise((resolve)=\u003e{\n      setTimeout(resolve, 3000);\n    })\n    console.log({\n      expId:params.expId,\n      id:params.id\n    })\n  }\n}\n```\n\n## 限流\n有时需要限制每个用户调用某个接口的频率, 以防止非正常的用户请求。\n\n```typescript\n//云引擎部分\nimport { Cloud, CloudParams } from 'leancloud-cloud-decorator'\n\nclass User {\n    @Cloud\u003c\u003e({\n        schema:{}\n        // 限流配置数组里的每一个条件，必须同时满足\n        rateLimit: [\n            {\n                //每个用户每秒最多只能请求2次此云函数\n                limit: 2,\n                timeUnit: 'second'\n            },\n            {\n                //每个用户每分钟最多只能请求30次此云函数\n                limit: 30,\n                timeUnit: 'minute'\n            }\n        ]\n    })\n    async GetTime() : Promise\u003cstring\u003e{\n        return new Date().toString()\n    }\n}\n\n```\n\n## 验证\n可给云函数添加需要验证才能调用的条件。比如，Post一个表单，新建一个专辑，申请一个工单等。对于这种Post类型的接口，如果不验证调用接口是否是真人的话，很容易被坏人用脚本工具，创建大量脏数据，同时浪费服务器资源。因此，我们把行为验证功能，集成进入云函数设置中。如果设置中开启了verify选项，则必须经过行为验证，才能调用。目前支持[极验Geetest](https://www.geetest.com/)与leancloud的短信验证码验证。未来可以增加更多种类的验证方式，例如地理位置验证，声纹验证，App验证，自定义验证等方式。\n\n `Cloud.GetVerifyParams` 用于返回短信验证码时\n  - 有登录态\n      - 该用户信息有mobilePhoneNumber字段。则直接给该电话号码发验证码，该接口返回值类型：`{ type: sms, sessionId, data: { mobilePhoneNumber }}`\n          - 如果用户已经不再使用之前的手机号码，则前端需要次级引导用户填入新的电话号码，将电话号码传入`Cloud.GetVerifyParams`\n      - 用户信息上没有mobilePhoneNumber字段。则**返回报错**，需要错误码和错误信息。这时候，请求的时候，需要向`Cloud.GetVerifyParams`传入电话号码。对于这种情况，前端需要在请求之前，尽量检查本地用户登陆状态上是否有保存电话，如果没有的话，直接在设计上就需要引导用户填入电话号码。以避免出现报错的情况。\n  - 没有登录态\n      - 没有登录态的时候，则每次发请求必须带上电话号码。如果没有电话号码，则返回报错。\n\n```typescript\n//云引擎部分\nimport { Cloud, CloudParams, init, VerifyError, MissingVerify } from 'leancloud-cloud-decorator'\n\n// 验证所需key添加在init中\ninit({\n  verify: {\n    geetest: {\n      geetest_id:{YOUR GEETEST_ID},\n      geetest_key: {YOUR GEETEST_KEY}\n    }\n  }\n  errorCallback:errorInfo =\u003e {\n    // 回调中捕获验证错误,返回自定义的错误码给前端识别\n    if (errorInfo.error instanceof VerifyError) {\n      return {code:411,message:'verify error'}\n    }else if (errorInfo.error instanceof MissingVerify) {\n      return {code:410,message:'missing verify'}\n    } else if (ikkError.error instanceof VerifyParamsMobileNumberUsedError) {\n      // 手机号已被使用\n      return {code:412,message:'MobilePhoneNumber have been used'}\n    } else if (ikkError.error instanceof VerifyParamsMissingUserOrMobilePhoneNumberError) {\n      // 手机号缺失\n      return {code:413,message:'missing user or mobilePhoneNumber'}\n    }\n    return errorInfo\n  }\n})\n\nclass User {\n    @Cloud\u003c\u003e({\n        schema:{}\n        // 在{timeUnit}单位时间内,被用户调用{count}需要进行{type}类型的验证,目前type类型仅支持geetest\n        verify: {\n          type: 'geetest',\n          count: 2,\n          timeUnit:'day'\n        }\n    })\n    async GetTime() : Promise\u003cstring\u003e{\n        return new Date().toString()\n    }\n    @Cloud\u003c\u003e({\n        schema:{}\n        // 在{timeUnit}单位时间内,被用户调用{count}需要进行{type}类型的验证,目前type类型仅支持geetest\n        verify: {\n          type: 'sms',\n          count: 2,\n          timeUnit:'day'\n        }\n    })\n    async GetTime2() : Promise\u003cstring\u003e{\n        return new Date().toString()\n    }\n}\n\n```\n\n1. 前端可通过云函数 Cloud.GetVerifyParams 获取验证所需的参数, 该云函数的返回值类型为：\n```typescript\ninterface VerifyParams{\n    /**\n     * 验证类型\n     */\n    type:VerifyType\n    /**\n     * 验证的sessionId\n     */\n    sessionId:string\n    /**\n     * 前端调用第三方验证时的参数\n     */\n    data:{ mobilePhoneNumber }|GeetestRegisterReturn\n}\ntype VerifyType = 'geetest' | 'sms'\n\n\nexport interface GeetestRegisterReturn{\n  gt: string\n  /**\n   * 正常时长度为32位,fallback时长度为34位.存储时, 统一只存32位长度\n   */\n  challenge: string\n  new_captcha: boolean\n  success:number\n}\n```\n2. geetest验时. 在客户端中，集成geetest的sdk，并将Cloud.GetVerifyParams返回的数据，传入geetest的sdk中。具体如下：\n``` ts\n// geetest前端执行例子\nvar verifyParams = await API.Cloud.GetVerifyParams({type:'geetest'})\nlet geetestResult\nfunction TestGeetest(data)\n{\n    // 调用 initGeetest 初始化参数\n    // 参数1：配置参数\n    // 参数2：回调，回调的第一个参数验证码对象，之后可以使用它调用相应的接口\n    initGeetest({\n     gt: data.gt,\n     challenge: data.challenge,\n     /* eslint-disable-next-line */\n     new_captcha: data.new_captcha, // 用于宕机时表示是新验证码的宕机\n     offline: !data.success, // 表示用户后台检测极验服务器是否宕机，一般不需要关注\n     product: 'bind', // 产品形式，包括：float，popup\n     width: '300px',\n     https: true\n     // 更多配置参数请参见：http://www.geetest.com/install/sections/idx-client-sdk.html#config\n   }, (captchaObj: any) =\u003e {\n     // 当验证实例准备就绪的时候，调用验证方法\n     captchaObj.onReady((e: any) =\u003e {\n       captchaObj.verify()\n     })\n     // 当验证成功之后，拿到验证参数继续传递给云函数\n     captchaObj.onSuccess(() =\u003e {\n       const geetestResult = captchaObj.getValidate()\n       // 拿到验证参数之后，调用云函数\n       API.User.GetTime({\n         cloudVerify:{ sessionId:verifyParams.sessionId, data:geetestResult }\n       })\n     })\n     captchaObj.onError((e: any) =\u003e {\n       console.log('gt onError', e)\n     })\n   })\n}\nTestGeetest(verifyParams.data)\n```\n\n3. 客户端将geetest的sdk返回的数据，传入需要验证的云函数。如果客户端的sdk是自动生成的话，则对于需要验证的云函数，可以看到参数类型上有cloudVerify这个键。\n若为sms短信验证, data内容为手机号与验证码\n\n```typescript\n{\n  cloudVerify?:{\n    sessionId:string,\n    data:{  \n      geetest_challenge:string\n      geetest_seccode:string\n      geetest_validate:string\n    }| {mobilePhoneNumber:string,smsCode:string}\n  }\n}\n```\n后端可单独调用验证接口给其他云函数使用. GetVerifyParams 获取验证参数, 通过 SetVerify 校验前端返回的验证结果\n```typescript\n// 后端例子\nimport { GetVerifyParams, SetVerify, CloudParams, Cloud } from 'leancloud-cloud-decorator'\ninterface RiskVerifyGeetestParams extends CloudParams {\n  sessionId:string\n  data:{\n    geetest_challenge:string\n    geetest_seccode:string\n    geetest_validate: string\n  }\n}\nclass Auth {\n    /**\n     * 获取验证参数\n     */\n    @Cloud({\n        schema:{}\n    })\n    async GetVerifyParams() {\n        return GetVerifyParams({type:'geetest'})\n    }\n    /**\n     * 验证有效性\n     */\n    @Cloud\u003cRiskVerifyGeetestParams\u003e({\n      schema: {\n        sessionId: Joi.string().required(),\n        data: Joi.object({\n          geetest_challenge: Joi.string().required(),\n          geetest_seccode: Joi.string().required(),\n          geetest_validate: Joi.string().required(),\n        })\n      }\n    })\n    async Verify(params:RiskVerifyGeetestParams) {\n        // @ts-ignore\n        await SetVerify(Object.assign({type:'geetest'},params))\n    }\n}\n```\n\n4. 对于设置了行为验证限流的云函数，并不是每一次调用都需要设置cloudVerify。客户端可以在正常调用抛出行为验证限流错误的时候，再进行验证。流程如下：\n``` ts\n// 前端调用例子\ntry{\n    await API.User.GetTime({})\n}catch(error){\n    // 后端在errorCallback回调中捕获验证错误,返回特定的错误码\n    if(error.code == 410){\n        API.User.GetTime({\n            cloudVerify:{ sessionId:verifyParams.sessionId, data:geetestResult }\n        })\n    }\n}\n```\n\n## 自动生成前端SDK\n通过项目根目录下的 lcc-config.json 配置文件, 配置需要生成的前端SDK平台。目前暂时不支持配置registry。模块都会发布到npm官方的registry下。如需要私有模块的话，考虑先使用npm的付费版。\n```json\n{\n    \"platforms\": {\n        \"web_user\": {\n            \"package\": \"@namespace/web-user\" // 配置web_user平台对应的npm包名称\n        },\n        \"weapp\": {\n            \"package\": \"@namespace/weapp\"\n        }\n    }\n}\n```\n安装模块时会通过 lcc-config.json 中的platforms字段生成模块中的平台的语法提示\n```typescript\n//云引擎部分\nimport { Cloud, CloudParams,Platform } from 'leancloud-cloud-decorator'\n\nclass User {\n    //定义一个,每过一小时,刷新一次时间信息的云函数\n    @Cloud\u003c\u003e({\n        schema:{}\n        //只生成 web_user 平台的API\n        platforms: ['web_user']\n    })\n    async GetTime() : Promise\u003cstring\u003e{\n        return new Date().toString()\n    }\n}\n\n```\n也可手动通过 lcc-config 应用配置.\n\n当lcc-config.json 的设置改变时候,必须手工执行 lcc-config 以应用配置\n```shell\n$ npx lcc-config\n```\n生成SDK的命令为\n```shell\n$ npx lcc 平台名\n```\n平台必须存在于 lcc-config.json 配置文件中, platforms字段中\n\n```shell\n$ npx lcc web_user\n```\n会在 \n\nrelease/api/web_user/src/lib\n\n生成sdk代码\n目前需要预先设置好项目,ts环境和index.ts代码\n\nindex.ts代码为\n```typescript\n// release/api/web_user/src/index.ts\nimport AV from 'leancloud-storage'\nimport sdkInfo from './info'\n\ntype CloudFunc = (name: string, data?: any, options?: AV.AuthOptions) =\u003e Promise\u003cany\u003e;\nlet __run: CloudFunc\nlet __rpc: CloudFunc\n\nexport function run(name: string, data?: any, options?: AV.AuthOptions): Promise\u003cany\u003e {\n  return __run(name, Object.assign(data || {},sdkInfo) , options)\n}\nexport function rpc(name: string, data?: any, options?: AV.AuthOptions): Promise\u003cany\u003e {\n  return __rpc(name, Object.assign(data || {},sdkInfo) , options)\n}\n\n/**\n * \n * @param av - AV空间对象, 调用sdk.init(AV) 即可\n */\nexport function init(av: {\n  version:string,\n  Cloud: {\n    run: CloudFunc,\n    rpc: CloudFunc\n  }\n}) {\n  let { Cloud } = av\n  __run = Cloud.run\n  __rpc = Cloud.rpc\n  sdkInfo.version = av.version\n}\n\nexport * from './lib';  \n```\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fparaself%2Fleancloud-cloud-decorator","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fparaself%2Fleancloud-cloud-decorator","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fparaself%2Fleancloud-cloud-decorator/lists"}