Skip to content

Commit

Permalink
feat(xo-server): support reading JSON records in Redis
Browse files Browse the repository at this point in the history
This allows forward compatibility with future versions which will use JSON records in the future.
  • Loading branch information
julien-f committed Oct 23, 2023
1 parent eb7de4f commit 7c009b0
Showing 1 changed file with 22 additions and 7 deletions.
29 changes: 22 additions & 7 deletions packages/xo-server/src/collection/redis.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,8 @@ export default class Redis extends Collection {
)

const idsIndex = `${prefix}_ids`
await asyncMapSettled(redis.sMembers(idsIndex), id =>
redis.hGetAll(`${prefix}:${id}`).then(values =>
await asyncMapSettled(redis.sMembers(idsIndex), id => {
return this.#get(`${prefix}:${id}`).then(values =>
values == null
? redis.sRem(idsIndex, id) // entry no longer exists
: asyncMapSettled(indexes, index => {
Expand All @@ -96,17 +96,16 @@ export default class Redis extends Collection {
}
})
)
)
})
}

_extract(ids) {
const prefix = this.prefix + ':'
const { redis } = this

const models = []
return Promise.all(
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 (isEmpty(model)) {
return
Expand Down Expand Up @@ -144,7 +143,7 @@ export default class Redis extends Collection {

// remove the previous values from indexes
if (indexes.length !== 0) {
const previous = await redis.hGetAll(`${prefix}:${id}`)
const previous = await this.#get(`${prefix}:${id}`)
await asyncMapSettled(indexes, index => {
const value = previous[index]
if (value !== undefined) {
Expand Down Expand Up @@ -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) {
const { prefix, redis } = this

Expand Down Expand Up @@ -227,7 +242,7 @@ export default class Redis extends Collection {
promise = Promise.all([
promise,
asyncMapSettled(ids, id =>
redis.hGetAll(`${prefix}:${id}`).then(
this.#get(`${prefix}:${id}`).then(
values =>
values != null &&
asyncMapSettled(indexes, index => {
Expand Down

0 comments on commit 7c009b0

Please sign in to comment.