Skip to content

Commit

Permalink
初始化项目
Browse files Browse the repository at this point in the history
  • Loading branch information
adaex committed May 23, 2020
1 parent e7e988c commit 43842e4
Show file tree
Hide file tree
Showing 10 changed files with 438 additions and 1 deletion.
7 changes: 7 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/.idea/
/node_modules/
/dist/

.DS_Store
npm-debug.log
yarn-error.log
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2020 COA

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
7 changes: 6 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,6 @@
# coa-redis
# coa-redis

[![GitHub license](https://img.shields.io/badge/license-MIT-green.svg?style=flat-square)](LICENSE)
[![npm version](https://img.shields.io/npm/v/coa-redis.svg?style=flat-square)](https://www.npmjs.org/package/coa-redis)
[![npm downloads](https://img.shields.io/npm/dm/coa-redis.svg?style=flat-square)](http://npm-stat.com/charts.html?package=coa-redis)
[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](https://github.com/coajs/coa-redis/pulls)
34 changes: 34 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"name": "coa-redis",
"version": "1.0.4",
"description": "redis component for coa",
"keywords": [
"coajs",
"coa",
"redis"
],
"license": "MIT",
"author": "Aex",
"homepage": "https://github.com/coajs/coa-redis",
"repository": {
"type": "git",
"url": "https://github.com/coajs/coa-redis.git"
},
"scripts": {
"dev": "tsc -w",
"build": "rm -rf dist && tsc && cp package.json dist",
"npm-publish": "yarn build && yarn version --patch && cp package.json README.md dist && cd dist && npm publish"
},
"dependencies": {
"@types/ioredis": "^4.16.2",
"coa-echo": "^1.0.8",
"coa-env": "^1.0.2",
"coa-error": "^1.0.2",
"coa-helper": "^1.0.5",
"ioredis": "^4.17.1"
},
"devDependencies": {
"@types/node": "^14.0.5",
"typescript": "^3.9.3"
}
}
146 changes: 146 additions & 0 deletions src/cache.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
import { env } from 'coa-env'
import { die } from 'coa-error'
import { _ } from 'coa-helper'
import redis from './redis'
import { Dic } from './typing'

const ms_ttl = 30 * 24 * 3600 * 1000
const prefix = env.redis.prefix.toString() || 'coa-d0'

declare global {
type CacheDelete = [string, string[]]
}

export default new class {

redis = redis

// 设置
async set (nsp: string, id: string, value: any, ms: number = ms_ttl) {
ms > 0 || die.hint('cache hash ms 必须大于0')
const expire = _.now() + ms
const data = this.encode(value, expire)
return await redis.io.hset(this.key(nsp), id, data)
}

// 批量设置
async mSet (nsp: string, values: Dic<any>, ms: number = ms_ttl) {
ms > 0 || die.error('cache hash ms 必须大于0')
_.keys(values).length > 0 || die.error('cache hash values值的数量 必须大于0')
const expire = Date.now() + ms
const data = {} as Dic<any>
_.forEach(values, (v, k) => data[k] = this.encode(v, expire))
return await redis.io.hmset(this.key(nsp), data)
}

// 获取
async get (nsp: string, id: string) {
const ret = await redis.io.hget(this.key(nsp), id) || ''
return this.decode(ret, _.now())
}

// 批量获取
async mGet (nsp: string, ids: string[]) {
const ret = await redis.io.hmget(this.key(nsp), ...ids)
const result = {} as Dic<any>
const time = _.now()
_.forEach(ids, (id, i) => result[id] = this.decode(ret[i], time))
return result
}

// 获取
async warp<T> (nsp: string, id: string, worker: () => Promise<T>, ms = ms_ttl) {
let result = await this.get(nsp, id)
if (result === undefined) {
result = await worker()
ms > 0 && await this.set(nsp, id, result, ms)
}
return result as T
}

// 获取
async mWarp<T> (nsp: string, ids: string[], worker: (ids: string[]) => Promise<T>, ms = ms_ttl) {
const result = await this.mGet(nsp, ids)

const newIds = [] as string[]
_.forEach(ids, id => {
if (result[id] === undefined) newIds.push(id)
})

if (newIds.length) {
const newResult = await worker(newIds) as any
_.forEach(newIds, id => {
if (!newResult[id]) newResult[id] = null
})
ms > 0 && await this.mSet(nsp, newResult, ms)
_.extend(result, newResult)
}

return result
}

// 删除
async delete (nsp: string, ids: string[] = []) {
if (ids.length)
return await redis.io.hdel(this.key(nsp), ...ids)
else
return await redis.io.del(this.key(nsp))
}

// 删除
async mDelete (deleteIds: CacheDelete[]) {
if (deleteIds.length === 0)
return 0
else if (deleteIds.length === 1)
return await this.delete(...deleteIds[0])

const pipeline = redis.io.pipeline()
deleteIds.forEach(([nsp, ids]) => {
ids.length ? pipeline.hdel(this.key(nsp), ...ids) : pipeline.del(this.key(nsp))
})
return await pipeline.exec()
}

// 清除无效的缓存
async clearUseless () {
const now = _.now()
const keys1 = await redis.io.keys(this.key('*'))
for (const i1 in keys1) {
const key1 = keys1[i1]
const keys2 = await redis.io.hkeys(key1) as string[]
for (const i2 in keys2) {
const key2 = keys2[i2]
const value = await redis.io.hget(key1, key2) || ''
const expire = _.toInteger(value.substr(1, 13))
if (expire < now) await redis.io.hdel(key1, key2)
}
}
}

// 清楚指定命名空间的缓存
async clear (nsp: string = '') {
const keys = await redis.io.keys(this.key(nsp + '*'))
return keys.length ? await redis.io.del(...keys) : 0
}

// 设置nsp
public key (nsp: string) {
return prefix + ':' + nsp
}

private encode (value: any, expire: number) {
if (value === undefined) value = null
return JSON.stringify([expire, value])
}

private decode (value: string | null, time: number) {
if (!value) return undefined
try {
const data = JSON.parse(value)
const expire = data[0] || 0
return expire < time ? undefined : data[1]
} catch (e) {
return undefined
}
}
}
5 changes: 5 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import cache from './cache'
import redis from './redis'
import { RedisEnv } from './typing'

export { redis, cache, RedisEnv }
19 changes: 19 additions & 0 deletions src/redis.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { echo } from 'coa-echo'
import { env } from 'coa-env'
import * as Redis from 'ioredis'

const redis = new Redis({
port: env.redis.port,
host: env.redis.host,
password: env.redis.password,
db: env.redis.db,
lazyConnect: true,
})

env.redis.trace && redis.monitor((err, monitor) => {
monitor.on('monitor', (time, args, source, database) => {
echo.grey('* Redis: [%s] %s', database, args)
})
})

export default { io: redis }
18 changes: 18 additions & 0 deletions src/typing.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
export interface Dic<T> {
[key: string]: T
}

export interface RedisEnv {
host: string,
port: number,
db: number,
password: string,
prefix: string,
trace: boolean
}

declare module 'coa-env' {
interface Env {
redis: RedisEnv
}
}
12 changes: 12 additions & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"compilerOptions": {
"strict": true,
"module": "commonjs",
"target": "esnext",
"outDir": "dist",
"declaration": true
},
"include": [
"src"
]
}
Loading

0 comments on commit 43842e4

Please sign in to comment.