@seedprotocol/sdk 0.1.53 → 0.1.54

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/dist/{index-DcXK4ERW.js → index-DQKd-s2Q.js} +597 -456
  2. package/dist/index-DQKd-s2Q.js.map +1 -0
  3. package/dist/{index-5a9z-kqT.js → index-NmD9sjcJ.js} +2 -2
  4. package/dist/index-NmD9sjcJ.js.map +1 -0
  5. package/dist/main.js +1 -1
  6. package/dist/{seed.schema.config-BtfzZOfM.js → seed.schema.config-OyHsE0Zl.js} +2 -2
  7. package/dist/{seed.schema.config-BtfzZOfM.js.map → seed.schema.config-OyHsE0Zl.js.map} +1 -1
  8. package/dist/src/ItemProperty.ts +114 -68
  9. package/dist/src/createMetadata.ts +36 -0
  10. package/dist/src/getItem.ts +12 -37
  11. package/dist/src/getItemProperty.ts +35 -0
  12. package/dist/src/getItems.ts +11 -18
  13. package/dist/src/getVersionData.ts +36 -48
  14. package/dist/src/hydrateFromDb.ts +11 -15
  15. package/dist/src/propertyMachine.ts +18 -2
  16. package/dist/src/saveValueToDb.ts +183 -69
  17. package/dist/src/syncDbWithEas.ts +1 -1
  18. package/dist/src/versionData.ts +24 -0
  19. package/dist/types/src/browser/db/read/getItem.d.ts.map +1 -1
  20. package/dist/types/src/browser/db/read/getItemProperty.d.ts +6 -0
  21. package/dist/types/src/browser/db/read/getItemProperty.d.ts.map +1 -0
  22. package/dist/types/src/browser/db/read/getItems.d.ts.map +1 -1
  23. package/dist/types/src/browser/db/read/getVersionData.d.ts +5 -14
  24. package/dist/types/src/browser/db/read/getVersionData.d.ts.map +1 -1
  25. package/dist/types/src/browser/db/read/subqueries/versionData.d.ts +70 -0
  26. package/dist/types/src/browser/db/read/subqueries/versionData.d.ts.map +1 -0
  27. package/dist/types/src/browser/db/write/createMetadata.d.ts +6 -0
  28. package/dist/types/src/browser/db/write/createMetadata.d.ts.map +1 -0
  29. package/dist/types/src/browser/item/Item.d.ts +1 -7
  30. package/dist/types/src/browser/item/Item.d.ts.map +1 -1
  31. package/dist/types/src/browser/property/ItemProperty.d.ts +12 -5
  32. package/dist/types/src/browser/property/ItemProperty.d.ts.map +1 -1
  33. package/dist/types/src/browser/property/actors/hydrateFromDb.d.ts.map +1 -1
  34. package/dist/types/src/browser/property/actors/saveValueToDb.d.ts +9 -1
  35. package/dist/types/src/browser/property/actors/saveValueToDb.d.ts.map +1 -1
  36. package/dist/types/src/browser/property/index.d.ts +9 -9
  37. package/dist/types/src/browser/property/propertyMachine.d.ts.map +1 -1
  38. package/dist/types/src/types/item.d.ts +17 -0
  39. package/dist/types/src/types/item.d.ts.map +1 -1
  40. package/dist/types/src/types/property.d.ts +9 -0
  41. package/dist/types/src/types/property.d.ts.map +1 -1
  42. package/package.json +1 -1
  43. package/dist/index-5a9z-kqT.js.map +0 -1
  44. package/dist/index-DcXK4ERW.js.map +0 -1
@@ -1,4 +1,4 @@
1
- export { f as GET_ALL_PROPERTIES_FOR_ALL_VERSIONS, e as GET_PROPERTIES, G as GET_SCHEMAS, a as GET_SEEDS, b as GET_SEED_IDS, c as GET_STORAGE_TRANSACTION_ID, d as GET_VERSIONS, I as Item, g as itemMachineAll, i as itemMachineSingle } from './index-DcXK4ERW.js';
1
+ export { f as GET_ALL_PROPERTIES_FOR_ALL_VERSIONS, e as GET_PROPERTIES, G as GET_SCHEMAS, a as GET_SEEDS, b as GET_SEED_IDS, c as GET_STORAGE_TRANSACTION_ID, d as GET_VERSIONS, I as Item, g as itemMachineAll, i as itemMachineSingle } from './index-DQKd-s2Q.js';
2
2
  import './constants-BLctWkrn.js';
3
3
  import 'path';
4
4
  import 'reflect-metadata';
@@ -27,4 +27,4 @@ import 'arweave';
27
27
  import 'react';
28
28
  import 'use-immer';
29
29
  import '@xstate/react';
30
- //# sourceMappingURL=index-5a9z-kqT.js.map
30
+ //# sourceMappingURL=index-NmD9sjcJ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index-NmD9sjcJ.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
package/dist/main.js CHANGED
@@ -1,4 +1,4 @@
1
- export { h as ImageSrc, I as Item, j as ItemProperty, J as Json, L as List, M as Model, P as Property, R as Relation, T as Text, s as client, t as getCorrectId, r as getGlobalService, m as useCreateItem, o as useDeleteItem, p as useGlobalServiceStatus, k as useItem, l as useItemProperties, n as useItemProperty, u as useItems, q as useServices, w as withSeed } from './index-DcXK4ERW.js';
1
+ export { h as ImageSrc, I as Item, j as ItemProperty, J as Json, L as List, M as Model, P as Property, R as Relation, T as Text, s as client, t as getCorrectId, r as getGlobalService, m as useCreateItem, o as useDeleteItem, p as useGlobalServiceStatus, k as useItem, l as useItemProperties, n as useItemProperty, u as useItems, q as useServices, w as withSeed } from './index-DQKd-s2Q.js';
2
2
  import 'immer';
3
3
  import 'reflect-metadata';
4
4
  import './constants-BLctWkrn.js';
@@ -1,6 +1,6 @@
1
1
  import { _ as __decorate, a as __metadata } from './constants-BLctWkrn.js';
2
2
  import 'drizzle-orm';
3
- import { T as Text, M as Model } from './index-DcXK4ERW.js';
3
+ import { T as Text, M as Model } from './index-DQKd-s2Q.js';
4
4
  import 'react';
5
5
  import 'reflect-metadata';
6
6
  import 'xstate';
@@ -74,4 +74,4 @@ const models = {
74
74
  };
75
75
 
76
76
  export { models };
77
- //# sourceMappingURL=seed.schema.config-BtfzZOfM.js.map
77
+ //# sourceMappingURL=seed.schema.config-OyHsE0Zl.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"seed.schema.config-BtfzZOfM.js","sources":["../../src/shared/configs/seed.schema.config.ts"],"sourcesContent":["import { Model, Text } from '@/browser'\n\n@Model\nclass Seed {\n @Text() uid!: string\n @Text() type!: string\n}\n\n@Model\nclass Version {\n @Text() seedUid!: string\n @Text() note!: string\n}\n\n@Model\nclass Metadata {\n @Text() key!: string\n @Text() value!: string\n}\n\nexport const models = {\n Seed,\n Version,\n Metadata,\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGA,IAAM,IAAI,GAAV,MAAM,IAAI,CAAA;CAGT;AAFS,UAAA,CAAA;AAAP,IAAA,IAAI,EAAE;;AAAa,CAAA,EAAA,IAAA,CAAA,SAAA,EAAA,KAAA,EAAA,KAAA,CAAA,CAAA;AACZ,UAAA,CAAA;AAAP,IAAA,IAAI,EAAE;;AAAc,CAAA,EAAA,IAAA,CAAA,SAAA,EAAA,MAAA,EAAA,KAAA,CAAA,CAAA;AAFjB,IAAI,GAAA,UAAA,CAAA;IADT;AACK,CAAA,EAAA,IAAI,CAGT;AAGD,IAAM,OAAO,GAAb,MAAM,OAAO,CAAA;CAGZ;AAFS,UAAA,CAAA;AAAP,IAAA,IAAI,EAAE;;AAAiB,CAAA,EAAA,OAAA,CAAA,SAAA,EAAA,SAAA,EAAA,KAAA,CAAA,CAAA;AAChB,UAAA,CAAA;AAAP,IAAA,IAAI,EAAE;;AAAc,CAAA,EAAA,OAAA,CAAA,SAAA,EAAA,MAAA,EAAA,KAAA,CAAA,CAAA;AAFjB,OAAO,GAAA,UAAA,CAAA;IADZ;AACK,CAAA,EAAA,OAAO,CAGZ;AAGD,IAAM,QAAQ,GAAd,MAAM,QAAQ,CAAA;CAGb;AAFS,UAAA,CAAA;AAAP,IAAA,IAAI,EAAE;;AAAa,CAAA,EAAA,QAAA,CAAA,SAAA,EAAA,KAAA,EAAA,KAAA,CAAA,CAAA;AACZ,UAAA,CAAA;AAAP,IAAA,IAAI,EAAE;;AAAe,CAAA,EAAA,QAAA,CAAA,SAAA,EAAA,OAAA,EAAA,KAAA,CAAA,CAAA;AAFlB,QAAQ,GAAA,UAAA,CAAA;IADb;AACK,CAAA,EAAA,QAAQ,CAGb;AAEY,MAAA,MAAM,GAAG;IACpB,IAAI;IACJ,OAAO;IACP,QAAQ;;;;;"}
1
+ {"version":3,"file":"seed.schema.config-OyHsE0Zl.js","sources":["../../src/shared/configs/seed.schema.config.ts"],"sourcesContent":["import { Model, Text } from '@/browser'\n\n@Model\nclass Seed {\n @Text() uid!: string\n @Text() type!: string\n}\n\n@Model\nclass Version {\n @Text() seedUid!: string\n @Text() note!: string\n}\n\n@Model\nclass Metadata {\n @Text() key!: string\n @Text() value!: string\n}\n\nexport const models = {\n Seed,\n Version,\n Metadata,\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGA,IAAM,IAAI,GAAV,MAAM,IAAI,CAAA;CAGT;AAFS,UAAA,CAAA;AAAP,IAAA,IAAI,EAAE;;AAAa,CAAA,EAAA,IAAA,CAAA,SAAA,EAAA,KAAA,EAAA,KAAA,CAAA,CAAA;AACZ,UAAA,CAAA;AAAP,IAAA,IAAI,EAAE;;AAAc,CAAA,EAAA,IAAA,CAAA,SAAA,EAAA,MAAA,EAAA,KAAA,CAAA,CAAA;AAFjB,IAAI,GAAA,UAAA,CAAA;IADT;AACK,CAAA,EAAA,IAAI,CAGT;AAGD,IAAM,OAAO,GAAb,MAAM,OAAO,CAAA;CAGZ;AAFS,UAAA,CAAA;AAAP,IAAA,IAAI,EAAE;;AAAiB,CAAA,EAAA,OAAA,CAAA,SAAA,EAAA,SAAA,EAAA,KAAA,CAAA,CAAA;AAChB,UAAA,CAAA;AAAP,IAAA,IAAI,EAAE;;AAAc,CAAA,EAAA,OAAA,CAAA,SAAA,EAAA,MAAA,EAAA,KAAA,CAAA,CAAA;AAFjB,OAAO,GAAA,UAAA,CAAA;IADZ;AACK,CAAA,EAAA,OAAO,CAGZ;AAGD,IAAM,QAAQ,GAAd,MAAM,QAAQ,CAAA;CAGb;AAFS,UAAA,CAAA;AAAP,IAAA,IAAI,EAAE;;AAAa,CAAA,EAAA,QAAA,CAAA,SAAA,EAAA,KAAA,EAAA,KAAA,CAAA,CAAA;AACZ,UAAA,CAAA;AAAP,IAAA,IAAI,EAAE;;AAAe,CAAA,EAAA,QAAA,CAAA,SAAA,EAAA,OAAA,EAAA,KAAA,CAAA,CAAA;AAFlB,QAAQ,GAAA,UAAA,CAAA;IADb;AACK,CAAA,EAAA,QAAQ,CAGb;AAEY,MAAA,MAAM,GAAG;IACpB,IAAI;IACJ,OAAO;IACP,QAAQ;;;;;"}
@@ -1,5 +1,11 @@
1
- import { ItemPropertyProps, PropertyMachineContext } from '@/types'
2
- import { ActorRefFrom, createActor, Subscription, waitFor } from 'xstate'
1
+ import { CreatePropertyInstanceProps, PropertyMachineContext } from '@/types'
2
+ import {
3
+ ActorRefFrom,
4
+ createActor,
5
+ SnapshotFrom,
6
+ Subscription,
7
+ waitFor,
8
+ } from 'xstate'
3
9
  import { BehaviorSubject, Subscriber } from 'rxjs'
4
10
  import { propertyMachine } from './propertyMachine'
5
11
  import { immerable } from 'immer'
@@ -12,9 +18,13 @@ import { getModel } from '@/browser/stores/modelClass'
12
18
  import { getCorrectId } from '@/browser/helpers'
13
19
  import { Static } from '@sinclair/typebox'
14
20
  import { TProperty } from '@/browser/property'
21
+ import { fs } from '@zenfs/core'
15
22
 
16
23
  const logger = debug('app:property:class')
17
24
 
25
+ type ItemPropertyService = ActorRefFrom<typeof propertyMachine>
26
+ type ItemPropertySnapshot = SnapshotFrom<typeof propertyMachine>
27
+
18
28
  type ItemPropertyFindProps = {
19
29
  propertyName: string
20
30
  propertyLocalId?: string
@@ -29,7 +39,7 @@ export class ItemProperty<PropertyType> {
29
39
  string,
30
40
  { instance: ItemProperty<any>; refCount: number }
31
41
  > = new Map()
32
- private readonly _service: ActorRefFrom<typeof propertyMachine>
42
+ private readonly _service: ItemPropertyService
33
43
  private _subject: BehaviorSubject<any>
34
44
  private readonly _isRelation: boolean = false
35
45
  private readonly _isList: boolean = false
@@ -47,11 +57,13 @@ export class ItemProperty<PropertyType> {
47
57
  propertyValue,
48
58
  seedUid,
49
59
  seedLocalId,
60
+ versionLocalId,
61
+ versionUid,
50
62
  itemModelName,
51
63
  propertyName,
52
64
  storageTransactionId,
53
65
  schemaUid,
54
- }: ItemPropertyProps) {
66
+ }: Partial<CreatePropertyInstanceProps>) {
55
67
  const ModelClass = getModel(itemModelName)
56
68
 
57
69
  if (!ModelClass) {
@@ -62,13 +74,13 @@ export class ItemProperty<PropertyType> {
62
74
  throw new Error(`Property name not provided`)
63
75
  }
64
76
 
65
- this._lastRenderedValue = propertyValue
66
-
67
77
  const serviceInput: Partial<PropertyMachineContext> = {
68
78
  propertyValue,
69
- seedUid,
70
79
  propertyName,
71
80
  seedLocalId,
81
+ seedUid,
82
+ versionLocalId,
83
+ versionUid,
72
84
  itemModelName,
73
85
  storageTransactionId,
74
86
  propertyRecordSchema: ModelClass.schema[propertyName],
@@ -130,65 +142,92 @@ export class ItemProperty<PropertyType> {
130
142
  this._service = createActor(propertyMachine, {
131
143
  input: serviceInput,
132
144
  })
133
- this._subscription = this._service.subscribe((snapshot) => {
134
- const { context } = snapshot
135
-
136
- // if (this.uid && !cacheHasProperty(this.uid)) {
137
- // addPropertyToCache(this)
138
- // }
139
- //
140
- // if (!this.uid && this.localId && !cacheHasProperty(this.localId,)) {
141
- // addPropertyToCache(this)
142
- // }
143
-
144
- if (context.seedLocalId) {
145
- const cacheKey = ItemProperty.cacheKey(
146
- context.seedLocalId,
147
- context.propertyName,
148
- )
149
- if (!ItemProperty.instanceCache.has(cacheKey)) {
150
- ItemProperty.instanceCache.set(cacheKey, {
151
- instance: this,
152
- refCount: 1,
153
- })
145
+ this._subscription = this._service.subscribe(
146
+ async (snapshot: ItemPropertySnapshot) => {
147
+ if (!snapshot || !snapshot.context) {
148
+ return
154
149
  }
155
- // this._updateResponseEvent = `property.${context.seedLocalId}.${this.propertyName}.save.response`
156
- // eventEmitter.addListener(
157
- // this._updateResponseEvent,
158
- // this._updateResponseListener,
159
- // )
160
- }
161
150
 
162
- const renderValue = context.renderValue || context.propertyValue
151
+ const { context } = snapshot
152
+ const { propertyRecordSchema } = context
153
+
154
+ // if (this.uid && !cacheHasProperty(this.uid)) {
155
+ // addPropertyToCache(this)
156
+ // }
157
+ //
158
+ // if (!this.uid && this.localId && !cacheHasProperty(this.localId,)) {
159
+ // addPropertyToCache(this)
160
+ // }
161
+
162
+ if (context.seedLocalId) {
163
+ const cacheKey = ItemProperty.cacheKey(
164
+ context.seedLocalId,
165
+ context.propertyName,
166
+ )
167
+ if (!ItemProperty.instanceCache.has(cacheKey)) {
168
+ ItemProperty.instanceCache.set(cacheKey, {
169
+ instance: this,
170
+ refCount: 1,
171
+ })
172
+ }
173
+ // this._updateResponseEvent = `property.${context.seedLocalId}.${this.propertyName}.save.response`
174
+ // eventEmitter.addListener(
175
+ // this._updateResponseEvent,
176
+ // this._updateResponseListener,
177
+ // )
178
+ }
163
179
 
164
- let transformedPropertyName = propertyName
180
+ let renderValue
165
181
 
166
- const skipTransform =
167
- internalPropertyNames.includes(propertyName) || !!this._alias
182
+ if (
183
+ propertyRecordSchema &&
184
+ propertyRecordSchema.storageType &&
185
+ propertyRecordSchema.storageType === 'ItemStorage' &&
186
+ context.resolvedValue &&
187
+ context.localStorageDir
188
+ ) {
189
+ const filePath = `/files/${context.localStorageDir}/${context.resolvedValue}`
190
+ const exists = await fs.promises.exists(filePath)
191
+ if (exists) {
192
+ renderValue = await fs.promises.readFile(filePath, 'utf-8')
193
+ }
194
+ }
168
195
 
169
- if (!skipTransform && transformedPropertyName.endsWith('Id')) {
170
- transformedPropertyName = transformedPropertyName.slice(0, -2)
171
- }
196
+ if (!renderValue) {
197
+ renderValue = context.renderValue || context.propertyValue
198
+ }
172
199
 
173
- if (!skipTransform && transformedPropertyName.endsWith('Ids')) {
174
- transformedPropertyName = transformedPropertyName.slice(0, -3)
175
- }
200
+ let transformedPropertyName = propertyName
176
201
 
177
- if (skipTransform && this._alias) {
178
- transformedPropertyName = this._alias
179
- }
202
+ const skipTransform =
203
+ internalPropertyNames.includes(propertyName) || !!this._alias
180
204
 
181
- if (skipTransform && !this._alias) {
182
- }
205
+ if (!skipTransform && transformedPropertyName.endsWith('Id')) {
206
+ transformedPropertyName = transformedPropertyName.slice(0, -2)
207
+ }
183
208
 
184
- this._subject.next(renderValue)
185
- if (context.seedLocalId) {
186
- eventEmitter.emit(`item.${itemModelName}.${context.seedLocalId}.update`)
187
- }
188
- if (context.seedUid) {
189
- eventEmitter.emit(`item.${itemModelName}.${context.seedUid}.update`)
190
- }
191
- })
209
+ if (!skipTransform && transformedPropertyName.endsWith('Ids')) {
210
+ transformedPropertyName = transformedPropertyName.slice(0, -3)
211
+ }
212
+
213
+ if (skipTransform && this._alias) {
214
+ transformedPropertyName = this._alias
215
+ }
216
+
217
+ if (skipTransform && !this._alias) {
218
+ }
219
+
220
+ this._subject.next(renderValue)
221
+ if (context.seedLocalId) {
222
+ eventEmitter.emit(
223
+ `item.${itemModelName}.${context.seedLocalId}.update`,
224
+ )
225
+ }
226
+ if (context.seedUid) {
227
+ eventEmitter.emit(`item.${itemModelName}.${context.seedUid}.update`)
228
+ }
229
+ },
230
+ )
192
231
 
193
232
  this._service.start()
194
233
  }
@@ -200,8 +239,11 @@ export class ItemProperty<PropertyType> {
200
239
  )
201
240
  }
202
241
 
203
- static create(props: ItemPropertyProps): ItemProperty<any> | undefined {
204
- const { propertyName, seedLocalId, seedUid } = props
242
+ static create(
243
+ props: Partial<CreatePropertyInstanceProps>,
244
+ ): ItemProperty<any> | undefined {
245
+ const { propertyName, seedLocalId, seedUid, versionLocalId, versionUid } =
246
+ props
205
247
  if (!propertyName || (!seedLocalId && !seedUid)) {
206
248
  return
207
249
  }
@@ -283,39 +325,43 @@ export class ItemProperty<PropertyType> {
283
325
  return this._service
284
326
  }
285
327
 
328
+ private _getSnapshot(): ItemPropertySnapshot {
329
+ return this._service.getSnapshot() as ItemPropertySnapshot
330
+ }
331
+
286
332
  get localId() {
287
- return this._service.getSnapshot().context.localId
333
+ return this._getSnapshot().context.localId
288
334
  }
289
335
 
290
336
  get uid() {
291
- return this._service.getSnapshot().context.uid
337
+ return this._getSnapshot().context.uid
292
338
  }
293
339
 
294
340
  get seedLocalId() {
295
- return this._service.getSnapshot().context.seedLocalId
341
+ return this._getSnapshot().context.seedLocalId
296
342
  }
297
343
 
298
344
  get seedUid() {
299
- return this._service.getSnapshot().context.seedUid
345
+ return this._getSnapshot().context.seedUid
300
346
  }
301
347
 
302
348
  get propertyName() {
303
349
  if (this._alias) {
304
350
  return this._alias
305
351
  }
306
- return this._service.getSnapshot().context.propertyName
352
+ return this._getSnapshot().context.propertyName
307
353
  }
308
354
 
309
355
  get itemModelName() {
310
- return this._service.getSnapshot().context.itemModelName
356
+ return this._getSnapshot().context.itemModelName
311
357
  }
312
358
 
313
359
  get propertyDef(): Static<typeof TProperty> | undefined {
314
- return this._service.getSnapshot().context.propertyRecordSchema
360
+ return this._getSnapshot().context.propertyRecordSchema
315
361
  }
316
362
 
317
363
  get status() {
318
- return this._service.getSnapshot().value
364
+ return this._getSnapshot().value
319
365
  }
320
366
 
321
367
  get alias() {
@@ -344,7 +390,7 @@ export class ItemProperty<PropertyType> {
344
390
  }
345
391
 
346
392
  get published(): boolean {
347
- return !!this._service.getSnapshot().context.uid
393
+ return !!this._getSnapshot().context.uid
348
394
  }
349
395
 
350
396
  subscribe(callback: Partial<Subscriber<any>>) {
@@ -0,0 +1,36 @@
1
+ import { metadata, MetadataType } from '@/shared/seedSchema'
2
+ import { getAppDb } from '../sqlWasmClient'
3
+ import { generateId } from '@/shared/helpers'
4
+ import { PropertyType } from '@/types'
5
+
6
+ type CreateMetadata = (
7
+ metadataValues: Partial<MetadataType>,
8
+ propertyRecordSchema?: PropertyType | undefined,
9
+ ) => Promise<MetadataType>
10
+
11
+ export const createMetadata: CreateMetadata = async (
12
+ metadataValues,
13
+ propertyRecordSchema?,
14
+ ) => {
15
+ const appDb = getAppDb()
16
+
17
+ metadataValues.localId = generateId()
18
+
19
+ if (
20
+ propertyRecordSchema &&
21
+ propertyRecordSchema.localStorageDir &&
22
+ propertyRecordSchema.storageType === 'ItemStorage'
23
+ ) {
24
+ metadataValues.refResolvedValue = `${metadataValues.localId}${propertyRecordSchema.filenameSuffix}`
25
+ metadataValues.refValueType = 'file'
26
+ }
27
+
28
+ return appDb
29
+ .insert(metadata)
30
+ .values({
31
+ ...metadataValues,
32
+ createdAt: Date.now(),
33
+ updatedAt: Date.now(),
34
+ })
35
+ .returning()
36
+ }
@@ -5,8 +5,9 @@ import { getSeedData } from '@/browser/db/read/getSeedData'
5
5
  import debug from 'debug'
6
6
  import { ItemData } from '@/types'
7
7
  import { getAppDb } from '../sqlWasmClient'
8
- import { seeds, versions } from '@/shared/seedSchema'
9
- import { and, count, eq, getTableColumns, max, SQL } from 'drizzle-orm'
8
+ import { seeds } from '@/shared/seedSchema'
9
+ import { and, eq, getTableColumns, gt, sql, SQL } from 'drizzle-orm'
10
+ import { getVersionData } from './subqueries/versionData'
10
11
 
11
12
  const logger = debug('app:db:queries:getItem')
12
13
 
@@ -56,44 +57,23 @@ export const getItemDataFromDb: GetItemDataFromDb = async ({
56
57
  whereClauses.push(eq(seeds.localId, seedLocalId))
57
58
  }
58
59
 
59
- // const uidWhereClause: SQL = seedUid
60
- // ? eq(seeds.uid, seedUid)
61
- // : isNull(seeds.uid)
62
- // const localWhereClause: SQL = seedLocalId
63
- // ? eq(seeds.localId, seedLocalId)
64
- // : isNull(seeds.localId)
65
-
66
- // whereClauses.push(or(localWhereClause, uidWhereClause) as SQL)
67
-
68
- const latestVersions = appDb.$with('latestVersions').as(
69
- appDb
70
- .select({
71
- localId: versions.localId,
72
- uid: versions.uid,
73
- seedLocalId: versions.seedLocalId,
74
- seedUid: versions.seedUid,
75
- })
76
- .from(versions)
77
- .groupBy(versions.seedLocalId),
78
- )
60
+ const versionData = getVersionData()
79
61
 
80
62
  const itemDataRows = await appDb
81
- .with(latestVersions)
63
+ .with(versionData)
82
64
  .select({
83
65
  ...rest,
84
66
  seedLocalId: seeds.localId,
85
67
  seedUid: seeds.uid,
86
- versionsCount: count(versions.localId),
87
- lastVersionPublishedAt: max(versions.attestationCreatedAt),
88
- latestVersionUid: latestVersions.uid,
68
+ versionsCount: versionData.versionsCount,
69
+ lastVersionPublishedAt: versionData.lastVersionPublishedAt,
70
+ latestVersionUid: versionData.latestVersionUid,
71
+ latestVersionLocalId: versionData.latestVersionLocalId,
89
72
  })
90
73
  .from(seeds)
91
- .leftJoin(versions, eq(versions.seedLocalId, seeds.localId))
92
- .leftJoin(
93
- latestVersions,
94
- eq(versions.seedLocalId, latestVersions.seedLocalId),
95
- )
96
- .where(and(...whereClauses))
74
+ .leftJoin(versionData, eq(seeds.localId, versionData.seedLocalId))
75
+ .where(and(...whereClauses, gt(versionData.versionsCount, 0)))
76
+ .orderBy(sql.raw('COALESCE(attestation_created_at, created_at) DESC'))
97
77
  .groupBy(seeds.localId)
98
78
 
99
79
  if (!itemDataRows || itemDataRows.length === 0) {
@@ -179,10 +159,5 @@ export const getItem: GetItem = async ({ modelName, seedLocalId, seedUid }) => {
179
159
  return
180
160
  }
181
161
 
182
- console.log(
183
- `[${modelName}.${seedLocalId}] [getItem] Creating Item`,
184
- itemInitObj,
185
- )
186
-
187
162
  return Item.create(itemInitObj)
188
163
  }
@@ -0,0 +1,35 @@
1
+ import { getAppDb } from '@/browser/db/sqlWasmClient'
2
+ import { metadata, MetadataType } from '@/shared/seedSchema'
3
+ import { and, eq, getTableColumns } from 'drizzle-orm'
4
+
5
+ type GetItemPropertyProps = Partial<MetadataType>
6
+
7
+ type GetItemPropertyData = (
8
+ props: GetItemPropertyProps,
9
+ ) => Promise<Partial<MetadataType>>
10
+
11
+ export const getItemPropertyData: GetItemPropertyData = async (props) => {
12
+ const appDb = getAppDb()
13
+
14
+ const whereClauses = []
15
+
16
+ const tableColumns = getTableColumns(metadata)
17
+
18
+ for (const [propertyName, propertyValue] of Object.entries(props)) {
19
+ if (Object.keys(tableColumns).includes(propertyName)) {
20
+ const column = tableColumns[propertyName]
21
+ whereClauses.push(eq(tableColumns[propertyName], propertyValue))
22
+ }
23
+ }
24
+
25
+ const queryRows = await appDb
26
+ .select()
27
+ .from(metadata)
28
+ .where(and(...whereClauses))
29
+
30
+ if (!queryRows || queryRows.length === 0) {
31
+ return
32
+ }
33
+
34
+ return queryRows[0]
35
+ }
@@ -1,18 +1,8 @@
1
1
  import { ItemData } from '@/types'
2
- import {
3
- and,
4
- count,
5
- desc,
6
- eq,
7
- isNotNull,
8
- isNull,
9
- max,
10
- or,
11
- SQL,
12
- sql,
13
- } from 'drizzle-orm'
14
- import { seeds, versions } from '@/shared/seedSchema'
2
+ import { and, eq, isNotNull, isNull, or, SQL, sql } from 'drizzle-orm'
3
+ import { seeds } from '@/shared/seedSchema'
15
4
  import { getAppDb } from '@/browser/db/sqlWasmClient'
5
+ import { getVersionData } from './subqueries/versionData'
16
6
 
17
7
  type GetItemsDataProps = {
18
8
  modelName?: string
@@ -51,22 +41,25 @@ export const getItemsData: GetItemsData = async ({
51
41
  )
52
42
  }
53
43
 
44
+ const versionData = getVersionData()
45
+
54
46
  let query = appDb
47
+ .with(versionData)
55
48
  .select({
56
49
  seedLocalId: seeds.localId,
57
50
  seedUid: seeds.uid,
58
51
  schemaUid: seeds.schemaUid,
59
52
  modelName: sql<string>`${modelName}`,
60
53
  attestationCreatedAt: seeds.attestationCreatedAt,
61
- versionsCount: count(versions.localId),
62
- lastVersionPublishedAt: max(versions.attestationCreatedAt),
63
- lastLocalUpdateAt: max(versions.createdAt),
54
+ versionsCount: versionData.versionsCount,
55
+ lastVersionPublishedAt: versionData.lastVersionPublishedAt,
56
+ lastLocalUpdateAt: versionData.lastLocalUpdateAt,
64
57
  createdAt: seeds.createdAt,
65
58
  })
66
59
  .from(seeds)
67
- .leftJoin(versions, eq(seeds.localId, versions.seedLocalId))
60
+ .leftJoin(versionData, eq(seeds.localId, versionData.seedLocalId))
68
61
  .where(and(...conditions))
69
- .orderBy(desc(seeds.createdAt))
62
+ .orderBy(sql.raw('COALESCE(attestation_created_at, created_at) DESC'))
70
63
  .groupBy(seeds.localId)
71
64
 
72
65
  const itemsData = (await query) as ItemData[]
@@ -1,58 +1,46 @@
1
- import { runQueryForStatement } from '../sqlWasmClient'
2
-
3
- type VersionData = {
4
- localId: string
5
- uid: string
6
- seedLocalId: string
7
- seedUid: string
8
- seedType: string
9
- note: string
10
- attestationCreatedAt: string
11
- attestationRaw: string
12
- createdAt: string
13
- updatedAt: string
14
- }
1
+ import { getAppDb } from '../sqlWasmClient'
2
+ import { versions, VersionsType } from '@/shared/seedSchema'
3
+ import { and, eq } from 'drizzle-orm'
15
4
 
16
5
  type GetVersionDataProps = {
17
- seedLocalId: string
6
+ localId?: string
7
+ uid?: string
8
+ seedLocalId?: string
18
9
  }
19
10
 
20
11
  type GetVersionData = (
21
12
  props: GetVersionDataProps,
22
- ) => Promise<VersionData | undefined>
23
-
24
- export const getVersionData: GetVersionData = async ({ seedLocalId }) => {
25
- const getVersionStatement = `SELECT local_id,
26
- uid,
27
- seed_local_id,
28
- seed_uid,
29
- seed_type,
30
- note,
31
- attestation_created_at,
32
- attestation_raw,
33
- created_at,
34
- updated_at
35
- FROM versions
36
- WHERE local_id = '${seedLocalId}';`
37
-
38
- const { rows } = await runQueryForStatement(getVersionStatement)
39
-
40
- if (!rows || !rows.length) {
41
- return
13
+ ) => Promise<VersionsType | undefined>
14
+
15
+ export const getVersionData: GetVersionData = async ({
16
+ localId,
17
+ seedLocalId,
18
+ uid,
19
+ }) => {
20
+ const appDb = getAppDb()
21
+
22
+ const whereClauses = []
23
+
24
+ if (seedLocalId) {
25
+ whereClauses.push(eq(versions.localId, seedLocalId))
26
+ }
27
+
28
+ if (localId) {
29
+ whereClauses.push(eq(versions.localId, localId))
30
+ }
31
+
32
+ if (uid) {
33
+ whereClauses.push(eq(versions.uid, uid))
42
34
  }
43
35
 
44
- const seedValues = rows[0]
45
-
46
- return {
47
- localId: seedValues[0],
48
- uid: seedValues[1],
49
- seedLocalId: seedValues[2],
50
- seedUid: seedValues[3],
51
- seedType: seedValues[4],
52
- note: seedValues[5],
53
- attestationCreatedAt: seedValues[6],
54
- attestationRaw: seedValues[7],
55
- createdAt: seedValues[8],
56
- updatedAt: seedValues[9],
36
+ const queryRows = await appDb
37
+ .select()
38
+ .from(versions)
39
+ .where(and(...whereClauses))
40
+
41
+ if (!queryRows || !queryRows.length) {
42
+ return
57
43
  }
44
+
45
+ return queryRows[0]
58
46
  }