queryable.js 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. const util = require('node:util')
  2. const _delete = Symbol('delete')
  3. const _append = Symbol('append')
  4. const sqBracketsMatcher = str => str.match(/(.+)\[([^\]]+)\]\.?(.*)$/)
  5. // replaces any occurrence of an empty-brackets (e.g: []) with a special Symbol(append) to represent it
  6. // this is going to be useful for the setter method that will push values to the end of the array when finding these
  7. const replaceAppendSymbols = str => {
  8. const matchEmptyBracket = str.match(/^(.*)\[\]\.?(.*)$/)
  9. if (matchEmptyBracket) {
  10. const [, pre, post] = matchEmptyBracket
  11. return [...replaceAppendSymbols(pre), _append, post].filter(Boolean)
  12. }
  13. return [str]
  14. }
  15. const parseKeys = key => {
  16. const sqBracketItems = new Set()
  17. sqBracketItems.add(_append)
  18. const parseSqBrackets = str => {
  19. const index = sqBracketsMatcher(str)
  20. // once we find square brackets, we recursively parse all these
  21. if (index) {
  22. const preSqBracketPortion = index[1]
  23. // we want to have a `new String` wrapper here in order to differentiate between multiple occurrences of the same string,
  24. // e.g: foo.bar[foo.bar] should split into { foo: { bar: { 'foo.bar': {} } }
  25. /* eslint-disable-next-line no-new-wrappers */
  26. const foundKey = new String(index[2])
  27. const postSqBracketPortion = index[3]
  28. // we keep track of items found during this step to make sure we don't try to split-separate keys that were defined within square brackets, since the key name itself might contain dots
  29. sqBracketItems.add(foundKey)
  30. // returns an array that contains either dot-separate items (that will be split apart during the next step OR the fully parsed keys read from square brackets
  31. // e.g: foo.bar[1.0.0].a.b -> ['foo.bar', '1.0.0', 'a.b']
  32. return [
  33. ...parseSqBrackets(preSqBracketPortion),
  34. foundKey,
  35. ...(postSqBracketPortion ? parseSqBrackets(postSqBracketPortion) : []),
  36. ]
  37. }
  38. // at the end of parsing, any usage of the special empty-bracket syntax (e.g: foo.array[]) has not yet been parsed
  39. // here we'll take care of parsing it and adding a special symbol to represent it in the resulting list of keys
  40. return replaceAppendSymbols(str)
  41. }
  42. const res = []
  43. // starts by parsing items defined as square brackets
  44. // those might be representing properties that have a dot in the name or just array indexes
  45. // e.g: foo[1.0.0] or list[0]
  46. const sqBracketKeys = parseSqBrackets(key.trim())
  47. for (const k of sqBracketKeys) {
  48. // keys parsed from square brackets should just be added to list of resulting keys as they might have dots as part of the key
  49. if (sqBracketItems.has(k)) {
  50. res.push(k)
  51. } else {
  52. // splits the dot-sep property names and add them to the list of keys
  53. /* eslint-disable-next-line no-new-wrappers */
  54. for (const splitKey of k.split('.')) {
  55. res.push(String(splitKey))
  56. }
  57. }
  58. }
  59. // returns an ordered list of strings in which each entry represents a key in an object defined by the previous entry
  60. return res
  61. }
  62. const getter = ({ data, key }, { unwrapSingleItemArrays = true } = {}) => {
  63. // keys are a list in which each entry represents the name of a property that should be walked through the object in order to return the final found value
  64. const keys = parseKeys(key)
  65. let _data = data
  66. let label = ''
  67. for (const k of keys) {
  68. // empty-bracket-shortcut-syntax is not supported on getter
  69. if (k === _append) {
  70. throw Object.assign(new Error('Empty brackets are not valid syntax for retrieving values.'), {
  71. code: 'EINVALIDSYNTAX',
  72. })
  73. }
  74. // extra logic to take into account printing array, along with its special syntax in which using a dot-sep property name after an array will expand it's results
  75. // e.g: arr.name -> arr[0].name=value, arr[1].name=value, ...
  76. const maybeIndex = Number(k)
  77. if (Array.isArray(_data) && !Number.isInteger(maybeIndex)) {
  78. _data = _data.reduce((acc, i, index) => {
  79. acc[`${label}[${index}].${k}`] = i[k]
  80. return acc
  81. }, {})
  82. return _data
  83. } else {
  84. if (!Object.hasOwn(_data, k)) {
  85. return undefined
  86. }
  87. _data = _data[k]
  88. }
  89. label += k
  90. }
  91. // these are some legacy expectations from the old API consumed by lib/view.js
  92. if (unwrapSingleItemArrays && Array.isArray(_data) && _data.length <= 1) {
  93. _data = _data[0]
  94. }
  95. return {
  96. [key]: _data,
  97. }
  98. }
  99. const setter = ({ data, key, value, force }) => {
  100. // setter goes to recursively transform the provided data obj
  101. // setting properties from the list of parsed keys
  102. // e.g: ['foo', 'bar', 'baz'] -> { foo: { bar: { baz: {} } }
  103. const keys = parseKeys(key)
  104. const setKeys = (_data, _key) => {
  105. // handles array indexes, converting valid integers to numbers
  106. // note that occurrences of Symbol(append) will throw so we just ignore these for now
  107. let maybeIndex = Number.NaN
  108. try {
  109. maybeIndex = Number(_key)
  110. } catch {
  111. // leave it NaN
  112. }
  113. if (!Number.isNaN(maybeIndex)) {
  114. _key = maybeIndex
  115. }
  116. // creates new array in case key is an index and the array obj is not yet defined
  117. const keyIsAnArrayIndex = _key === maybeIndex || _key === _append
  118. const dataHasNoItems = !Object.keys(_data).length
  119. if (keyIsAnArrayIndex && dataHasNoItems && !Array.isArray(_data)) {
  120. _data = []
  121. }
  122. // converting from array to an object is also possible, in case the user is using force mode
  123. // we should also convert existing arrays to an empty object if the current _data is an array
  124. if (force && Array.isArray(_data) && !keyIsAnArrayIndex) {
  125. _data = { ..._data }
  126. }
  127. // the _append key is a special key that is used to represent the empty-bracket notation
  128. // e.g: arr[] -> arr[arr.length]
  129. if (_key === _append) {
  130. if (!Array.isArray(_data)) {
  131. throw Object.assign(new Error(`Can't use append syntax in non-Array element`), {
  132. code: 'ENOAPPEND',
  133. })
  134. }
  135. _key = _data.length
  136. }
  137. // retrieves the next data object to recursively iterate on
  138. // throws if trying to override a literal value or add props to an array
  139. const next = () => {
  140. const haveContents = !force && _data[_key] != null && value !== _delete
  141. const shouldNotOverrideLiteralValue = !(typeof _data[_key] === 'object')
  142. // if the next obj to recurse is an array and the next key to be appended to the resulting obj is not an array index, then it should throw since we can't append arbitrary props to arrays
  143. const shouldNotAddPropsToArrays =
  144. typeof keys[0] !== 'symbol' && Array.isArray(_data[_key]) && Number.isNaN(Number(keys[0]))
  145. const overrideError = haveContents && shouldNotOverrideLiteralValue
  146. if (overrideError) {
  147. throw Object.assign(
  148. new Error(`Property ${_key} already exists and is not an Array or Object.`),
  149. { code: 'EOVERRIDEVALUE' }
  150. )
  151. }
  152. const addPropsToArrayError = haveContents && shouldNotAddPropsToArrays
  153. if (addPropsToArrayError) {
  154. throw Object.assign(new Error(`Can't add property ${key} to an Array.`), {
  155. code: 'ENOADDPROP',
  156. })
  157. }
  158. return typeof _data[_key] === 'object' ? _data[_key] || {} : {}
  159. }
  160. // sets items from the parsed array of keys as objects, recurses to setKeys in case there are still items to be handled
  161. // otherwise, it just sets the original value set by the user
  162. if (keys.length) {
  163. _data[_key] = setKeys(next(), keys.shift())
  164. } else {
  165. // handles special deletion cases for obj props / array items
  166. if (value === _delete) {
  167. if (Array.isArray(_data)) {
  168. _data.splice(_key, 1)
  169. } else {
  170. delete _data[_key]
  171. }
  172. } else {
  173. // finally, sets the value in its right place
  174. _data[_key] = value
  175. }
  176. }
  177. return _data
  178. }
  179. setKeys(data, keys.shift())
  180. }
  181. class Queryable {
  182. static ALL = ''
  183. #data = null
  184. constructor (obj) {
  185. if (!obj || typeof obj !== 'object') {
  186. throw Object.assign(new Error('Queryable needs an object to query properties from.'), {
  187. code: 'ENOQUERYABLEOBJ',
  188. })
  189. }
  190. this.#data = obj
  191. }
  192. query (queries, opts) {
  193. // this ugly interface here is meant to be a compatibility layer with the legacy API lib/view.js is consuming
  194. // if at some point we refactor that command then we can revisit making this nicer
  195. if (queries === Queryable.ALL) {
  196. return { [Queryable.ALL]: this.#data }
  197. }
  198. const q = query =>
  199. getter({
  200. data: this.#data,
  201. key: query,
  202. }, opts)
  203. if (Array.isArray(queries)) {
  204. let res = {}
  205. for (const query of queries) {
  206. res = { ...res, ...q(query) }
  207. }
  208. return res
  209. } else {
  210. return q(queries)
  211. }
  212. }
  213. // return the value for a single query if found; otherwise, returns undefined
  214. get (query) {
  215. const obj = this.query(query)
  216. if (obj) {
  217. return obj[query]
  218. }
  219. }
  220. // creates objects along the way for the provided `query` parameter and assigns `value` to the last property of the query chain
  221. set (query, value, { force } = {}) {
  222. setter({
  223. data: this.#data,
  224. key: query,
  225. value,
  226. force,
  227. })
  228. }
  229. // deletes the value of the property found at `query`
  230. delete (query) {
  231. setter({
  232. data: this.#data,
  233. key: query,
  234. value: _delete,
  235. })
  236. }
  237. toJSON () {
  238. return this.#data
  239. }
  240. [util.inspect.custom] () {
  241. return this.toJSON()
  242. }
  243. }
  244. module.exports = Queryable