当前位置: 首页 > 工具软件 > ioredis > 使用案例 >

ioredis自定义函数以及在ts声明文件库添加声明

储法
2023-12-01

在incude中添加声明文件夹:types/*
添加ts的配置文件:

// tsconfig.json
{
	"compilerOptions": {
		"experimentalDecorators": true,
		"module": "commonjs",
		"esModuleInterop": true,
		"allowSyntheticDefaultImports": true,
		"target": "es6",
		"noImplicitAny": true,
		"moduleResolution": "node",
		"sourceMap": true,
		"outDir": "dist",
		"baseUrl": ".",
		"newLine": "LF",
		"paths": {
			"*": [
				"node_modules/*",
			]
		}
	},
	"exclude": [
		"test/sources"
	],
	"include": [
		"src/**/*",
		"types/*"
	]
}

加载lua脚本的函数:

// src/loadScripts.ts
'use strict';
import { promises as fs } from "fs";
import path from "path";
const loadScripts = async () => {
	const commandsPath = path.join(__dirname, '../commands')
	const files = await fs.readdir(commandsPath);
	const luaFiles = files.filter(file => path.extname(file) == ".lua");
	return await Promise.all(luaFiles.map(async file => {
		const longName = path.basename(file, '.lua');
		const name = longName.split('-')[0];
		const numberOfKeys = parseInt(longName.split('-')[1]);
		const luaScript = await fs.readFile(path.join(commandsPath, file));
		return {
			name,
			options: {
				numberOfKeys,
				lua: luaScript.toString()
			}
		};
	}))
}
export default loadScripts 

测试脚本:

// commands/mymset-2.lua
local key1 = KEYS[1]
local key2 = KEYS[2]
local val1 = ARGV[1]
local val2 = ARGV[2]

redis.call('HMSET', 'a', key1, val1, key2, val2)
redis.call('PUBLISH', 'addjob', '123')
return 1

测试:

// src/index.ts
import Redis from "ioredis";
import "ioredis-plugin";
import { inspect } from "util";
import loadScripts from "./loadScripts";

const init = async () => {
	const scripts = await loadScripts();
	const sub = new Redis({
		host: 'localhost',
		port: 6379,
		password: '',
	})
	const pub = new Redis({
		host: 'localhost',
		port: 6379,
		password: '',
	})
	await sub.subscribe('addjob');

	sub.on('message', (channel, mess) => {
		console.log(mess);
	})
	sub.on('error', (err) => {
		console.log(`redis error:${inspect(err)}`);
		process.exit(1);
	});
	pub.on('error', (err) => {
		console.log(`redis error:${inspect(err)}`);
		process.exit(1);
	});

	scripts.map(script => {
		pub.defineCommand(script.name, script.options)
	})
	const resule = await pub.mymset("key1", "key2", "val1", "val2");
	console.log(resule)
}

init().catch(err => {
	console.log(err)
})
// types/ioredis-plugin/index.d.ts
import "ioredis";

declare module "ioredis" {

    interface Commands {
        mymset: (...keys: string[]) => Promise<string>;
    }

}

全局命名空间

import type { Dayjs } from 'dayjs';
declare namespace TT{
  interface A {
  	time: Dayjs;
  }
}
export = CardManage;
export as namespace CardManage;
 类似资料: