fix(xo-server/store): dont fail on serializing circular values

See https://github.com/vatesfr/xen-orchestra/pull/5397#discussion_r555170305
This commit is contained in:
Julien Fontanet
2021-01-14 14:59:08 +01:00
parent 752146028b
commit 14d06fe754
2 changed files with 22 additions and 5 deletions

View File

@@ -86,6 +86,7 @@
"iterable-backoff": "^0.1.0",
"jest-worker": "^26.3.0",
"js-yaml": "^3.10.0",
"json-stringify-safe": "^5.0.1",
"json-rpc-peer": "^0.17.0",
"json5": "^2.0.1",
"kindof": "^2.0.0",

View File

@@ -1,7 +1,11 @@
import jsonStringifySafe from 'json-stringify-safe'
import levelup from 'level-party'
import sublevel from 'subleveldown'
import { createLogger } from '@xen-orchestra/log'
import { ensureDir } from 'fs-extra'
const log = createLogger('xo:store')
// ===================================================================
const _levelHas = async function has(key, cb) {
@@ -27,6 +31,22 @@ const levelHas = db => {
// ===================================================================
const valueEncoding = {
buffer: false,
decode: JSON.parse,
encode: data => {
try {
return JSON.stringify(data)
} catch (error) {
log.warn(error)
// attempts to stringify by removing circular references
return jsonStringifySafe(data)
}
},
type: 'safe-json',
}
export default class {
constructor(xo, config) {
const dir = `${config.datadir}/leveldb`
@@ -34,10 +54,6 @@ export default class {
}
async getStore(namespace) {
return levelHas(
sublevel(await this._db, namespace, {
valueEncoding: 'json',
})
)
return levelHas(sublevel(await this._db, namespace, { valueEncoding }))
}
}