开发
如何为触发器和函数开发
为了帮助开发新的触发器和函数库,您可以使用触发器和函数 API的类型声明文件,这将允许您首选的开发环境提供自动完成功能和类型检查。您可以使用以下命令安装此信息
npm install https://gitpkg.now.sh/RedisGears/RedisGears/js_api --save-dev
或者,您也可以手动将其作为 devDependency 添加到您的 package.json
文件中
"devDependencies": {
"@redis/gears-api": "https://gitpkg.now.sh/RedisGears/RedisGears/js_api"
}
示例项目设置
为您的新触发器和函数项目创建空目录,my_first_project
。导航到该文件夹并运行以下命令
$ npm init -y -f
npm WARN using --force Recommended protections disabled.
Wrote to /home/work/my_first_project/package.json:
{
"name": "my_first_project",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
更新 package.json
以将 gears API 添加到 devDependencies
对象。
{
"name": "my_first_project",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"devDependencies": {
"@redis/gears-api": "https://gitpkg.now.sh/RedisGears/RedisGears/js_api"
},
"keywords": [],
"author": "",
"license": "ISC"
}
使用 npm install
安装依赖项。
创建一个新文件,index.js
,并导入 gears-api 模块。虽然此步骤并非严格必要,但这样做将在添加 registerFunction
时启用智能代码完成功能
#!js name=lib api_version=1.0
import { redis } from '@redis/gears-api';
redis.registerFunction("test", ()=>{
return "test";
});
要自动执行部署,请更新 package.json
中的 scripts
部分
"scripts": {
"deploy": "gears-api index.js"
}
现在,您可以使用以下命令将您的代码部署到 Redis Stack
> npm run deploy -- -r redis://127.0.0.1:6379
> deploy
> gears-api index.js
Deployed! :)
提供的 URL 应遵循以下格式
<redis[s]://[[username][:password]@][host][:port][/db-number]>
您现在可以运行您的 Redis Stack 函数
127.0.0.1:6379> TFCALL lib.test 0
"test"
使用第三方 npm
包的示例函数
如果您想在 Redis Stack 函数中使用第三方 npm
包,整个过程与之前讨论的几乎相同,只有一两处不同。
首先,您需要使用 npm install
安装您的包。在本示例中,math.js
库中的 pi
符号将用于一个计算圆形的面积的简单函数。
npm install mathjs
注意:您的 package.json
文件也将更新为新的依赖项。例如
"dependencies": {
"mathjs": "^12.0.0"
}
接下来,您需要将所需的符号导入到您的函数中。
#!js api_version=1.0 name=lib
import { redis } from '@redis/gears-api';
import { pi } from 'mathjs';
function calculateCircleArea(client, radius) {
return pi * radius * radius;
}
redis.registerFunction('calculateArea', calculateCircleArea);
按照上一节中描述的加载并运行您的新函数。