feat(xo-server): support reading JSON records in Redis

This allows forward compatibility with future versions which will use JSON records in the future.
This commit is contained in:
Julien Fontanet 2023-10-19 15:56:51 +02:00
parent eb7de4f2dd
commit 7c009b0fc0

View File

@ -85,8 +85,8 @@ export default class Redis extends Collection {
) )
const idsIndex = `${prefix}_ids` const idsIndex = `${prefix}_ids`
await asyncMapSettled(redis.sMembers(idsIndex), id => await asyncMapSettled(redis.sMembers(idsIndex), id => {
redis.hGetAll(`${prefix}:${id}`).then(values => return this.#get(`${prefix}:${id}`).then(values =>
values == null values == null
? redis.sRem(idsIndex, id) // entry no longer exists ? redis.sRem(idsIndex, id) // entry no longer exists
: asyncMapSettled(indexes, index => { : asyncMapSettled(indexes, index => {
@ -96,17 +96,16 @@ export default class Redis extends Collection {
} }
}) })
) )
) })
} }
_extract(ids) { _extract(ids) {
const prefix = this.prefix + ':' const prefix = this.prefix + ':'
const { redis } = this
const models = [] const models = []
return Promise.all( return Promise.all(
map(ids, id => { map(ids, id => {
return redis.hGetAll(prefix + id).then(model => { return this.#get(prefix + id).then(model => {
// If empty, consider it a no match. // If empty, consider it a no match.
if (isEmpty(model)) { if (isEmpty(model)) {
return return
@ -144,7 +143,7 @@ export default class Redis extends Collection {
// remove the previous values from indexes // remove the previous values from indexes
if (indexes.length !== 0) { if (indexes.length !== 0) {
const previous = await redis.hGetAll(`${prefix}:${id}`) const previous = await this.#get(`${prefix}:${id}`)
await asyncMapSettled(indexes, index => { await asyncMapSettled(indexes, index => {
const value = previous[index] const value = previous[index]
if (value !== undefined) { if (value !== undefined) {
@ -184,6 +183,22 @@ export default class Redis extends Collection {
) )
} }
async #get(key) {
const { redis } = this
let model
try {
model = await redis.hGetAll(key)
} catch (error) {
if (!error.message.startsWith('WRONGTYPE')) {
throw error
}
model = await redis.get(key).then(JSON.parse)
}
return model
}
_get(properties) { _get(properties) {
const { prefix, redis } = this const { prefix, redis } = this
@ -227,7 +242,7 @@ export default class Redis extends Collection {
promise = Promise.all([ promise = Promise.all([
promise, promise,
asyncMapSettled(ids, id => asyncMapSettled(ids, id =>
redis.hGetAll(`${prefix}:${id}`).then( this.#get(`${prefix}:${id}`).then(
values => values =>
values != null && values != null &&
asyncMapSettled(indexes, index => { asyncMapSettled(indexes, index => {