Created
March 17, 2024 02:14
-
-
Save maca134/38d06fdfa1b94e13a24f53f9be5c625c to your computer and use it in GitHub Desktop.
Redis Streams for Nodejs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Readable, Writable } from "stream"; | |
import { commandOptions, createClient } from "redis"; | |
export const createWriteStream = (client: ReturnType<typeof createClient>, key: string, opts?: { ttlMs?: number }) => | |
new Writable({ | |
objectMode: false, | |
construct: (callback) => | |
client | |
.del(key) | |
.then(() => callback()) | |
.catch(callback), | |
write: (chunk, _, callback) => | |
client | |
.append(key, chunk) | |
.then(() => callback()) | |
.catch(callback), | |
final: (callback) => | |
opts?.ttlMs | |
? client | |
.pExpire(key, opts?.ttlMs) | |
.then(() => callback()) | |
.catch(callback) | |
: callback(), | |
}); | |
export const createReadStream = (client: ReturnType<typeof createClient>, key: string) => { | |
let sent = 0; | |
return new Readable({ | |
objectMode: false, | |
async read(size) { | |
const data = await client.getRange( | |
commandOptions({ returnBuffers: true }), | |
key, | |
sent, | |
sent + size, | |
); | |
if (data.length === 0) { | |
this.push(null); | |
return; | |
} | |
sent += data.length; | |
this.push(data); | |
}, | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment