Advertisement
Guest User

Untitled

a guest
May 24th, 2019
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.98 KB | None | 0 0
  1. import * as _ from 'lodash'
  2. import * as IORedis from 'ioredis'
  3. import * as pkgup from 'read-pkg-up'
  4. import * as schedule from 'node-schedule'
  5.  
  6. export namespace Redis {
  7. export type Coms = string[][]
  8. export interface Event<T = any> {
  9. data: T
  10. name: string
  11. }
  12. }
  13.  
  14. export class Redis extends IORedis {
  15. private static opts(opts: IORedis.RedisOptions) {
  16. let pkgname = pkgup.sync({ cwd: __dirname }).pkg.name
  17. _.defaults(opts, {
  18. connectionName: _.trim(`${process.DEVELOPMENT && '[DEV]'} ${pkgname} ${opts.name}`),
  19. db: 0,
  20. host: process.env.REDIS_HOST || '127.0.0.1',
  21. password: process.env.REDIS_PASSWORD,
  22. port: _.parseInt(process.env.REDIS_PORT) || 6379,
  23. } as IORedis.RedisOptions)
  24. // if (!process.DEVELOPMENT) {
  25. // opts.path = '/var/run/redis_' + opts.port + '.sock'
  26. // _.unset(opts, 'host')
  27. // _.unset(opts, 'port')
  28. // }
  29. return opts
  30. }
  31.  
  32. constructor(opts: IORedis.RedisOptions) {
  33. super(Redis.opts(opts))
  34. }
  35.  
  36. async purge(rkey: string, pattern = ':*') {
  37. let keys = await this.keys(rkey + pattern)
  38. console.warn('PURGE ->', rkey + pattern, '->', keys.length)
  39. await this.coms(keys.map(v => ['del', v]))
  40. return keys
  41. }
  42.  
  43. async coms(coms = [] as Redis.Coms) {
  44. let results = ((await this.pipeline(coms).exec()) || []) as any[]
  45. for (let i = 0; i < results.length; i++) {
  46. if (results[i][0]) {
  47. throw new Error(`coms[${i}] ${coms[i]} results[${i}] ${results[i][0]}`)
  48. }
  49. results[i] = results[i][1]
  50. }
  51. return results
  52. }
  53.  
  54. fixHMget(hmget: any[], keys: string[]) {
  55. return hmget.reduce((target, value, index) => {
  56. target[keys[index]] = value
  57. return target
  58. }, {})
  59. }
  60.  
  61. toHset(from: any) {
  62. return Object.entries(from).reduce((target, [key, value]) => {
  63. target[key] = JSON.stringify(value)
  64. return target
  65. }, {})
  66. }
  67. fromHget(to: any) {
  68. for (let key in to) {
  69. to[key] = JSON.parse(to[key])
  70. }
  71. return to
  72. }
  73. }
  74.  
  75. export const redis = new Redis({ name: 'redis' })
  76. export default redis
  77.  
  78. setTimeout(() => schedule.scheduleJob('*/5 * * * * *', () => redis.ping()), 1000)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement