All files redis.js

93.44% Statements 57/61
72.73% Branches 8/11
92% Functions 23/25
93.33% Lines 56/60

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170                    7x                                                       7x     279x 279x 279x 1570x 1570x     279x 279x 279x                   22x 22x   294x 294x     1x 1x       22x 22x 206x     206x     22x 22x 22x   22x         22x     22x 9x     22x   14x       22x       4x 4x   4x 4x 4x 4x         4x 8x     8x 11x 11x     8x   8x               4x   4x   8x           4x       4x 68x 8x       8x     4x     22x 374x 248x     22x    
/**
 * @file src/redis.js.js
 * @copyright 2019-present Karim Alibhai. All rights reserved.
 */
 
import * as net from 'net'
 
import createDebug from 'debug'
import RedisParser from 'redis-parser'
 
const commands = [
	'ping',
 
	// KEY-VALUE
	'get',
	'set',
 
	// SET
	'sadd',
	'smembers',
	'srem',
	'scard',
 
	// STREAM
	'xack',
	'xadd',
	'xclaim',
	'xdel',
	'xgroup',
	'xpending',
	'xreadgroup',
 
	// SORTED SET
	'zadd',
	'zrangebyscore',
	'zrem',
]
 
const debug = createDebug('superq:redis')
 
function sendCommand(sock, cmdBuffer, cmd, args) {
	return new Promise((resolve, reject) => {
		let buffer = `*${1 + args.length}\r\n$${cmd.length}\r\n${cmd}\r\n`
		for (const arg of args) {
			const strArg = String(arg)
			buffer += `$${strArg.length}\r\n${strArg}\r\n`
		}
 
		debug(`Sending command: %j`, buffer)
		sock.write(buffer)
		cmdBuffer.push({ resolve, reject })
	})
}
 
export async function createRedis({
	host = 'localhost',
	port = 6379,
	db = 0,
	password,
} = {}) {
	const cmdBuffer = []
	const parser = new RedisParser({
		returnReply: reply => {
			const { resolve } = cmdBuffer.shift()
			resolve(reply)
		},
		returnError: error => {
			const { reject } = cmdBuffer.shift()
			reject(error)
		},
	})
 
	const sock = net.createConnection(port, host)
	sock.on('data', chunk => {
		Iif (debug.enabled) {
			debug(`Received chunk from redis: %j`, chunk.toString('utf8'))
		}
		parser.execute(chunk)
	})
 
	await new Promise((resolve, reject) => {
		sock.on('connect', () => {
			resolve()
		})
		sock.on('error', error => {
			reject(error)
		})
	})
 
	Iif (password) {
		await sendCommand(sock, cmdBuffer, 'AUTH', [password])
	}
	if (db !== 0) {
		await sendCommand(sock, cmdBuffer, 'SELECT', [String(db)])
	}
 
	const redis = {
		close() {
			return new Promise(resolve => sock.end(resolve))
		},
 
		sendCommand(cmd, args = []) {
			return sendCommand(sock, cmdBuffer, cmd, args)
		},
 
		multi() {
			const transactionBuffer = []
			const transaction = {
				async exec() {
					return new Promise((resolve, reject) => {
						const cmdResults = []
						let buffer = `*1\r\n$5\r\nMULTI\r\n`
						cmdBuffer.push({
							resolve() {},
							reject,
						})
 
						for (const { command, args } of transactionBuffer) {
							buffer += `*${args.length + 1}\r\n$${
								command.length
							}\r\n${command}\r\n`
							args.forEach(arg => {
								const strArg = String(arg)
								buffer += `$${strArg.length}\r\n${strArg}\r\n`
							})
 
							cmdBuffer.push({
								resolve() {
									cmdResults.push(null)
								},
								reject(err) {
									cmdResults.push(err)
								},
							})
						}
 
						cmdBuffer.push({
							resolve(results) {
								resolve(
									cmdResults.map((result, index) => {
										return [result, results[index]]
									}),
								)
							},
							reject,
						})
						sock.write(buffer + '*1\r\n$4\r\nEXEC\r\n')
					})
				},
			}
			commands.forEach(command => {
				transaction[command] = function(...args) {
					transactionBuffer.push({
						command,
						args,
					})
					return transaction
				}
			})
			return transaction
		},
	}
	commands.forEach(command => {
		redis[command] = function(...args) {
			return sendCommand(sock, cmdBuffer, command, args)
		}
	})
	return redis
}