Jelajahi Sumber

add the em.validateEntity method

Olivier Massot 1 tahun lalu
induk
melakukan
f19df91a90

+ 6 - 2
models/Access/Access.ts

@@ -1,4 +1,4 @@
-import { HasOne, Num, Uid, Attr } from 'pinia-orm/dist/decorators'
+import {HasOne, Num, Uid, Attr, Str} from 'pinia-orm/dist/decorators'
 import type { Historical } from '~/types/interfaces'
 import type { Historical } from '~/types/interfaces'
 import Person from '~/models/Person/Person'
 import Person from '~/models/Person/Person'
 import ApiModel from '~/models/ApiModel'
 import ApiModel from '~/models/ApiModel'
@@ -16,7 +16,8 @@ export default class Access extends ApiModel {
   @Uid()
   @Uid()
   declare id: number | string
   declare id: number | string
 
 
-  @HasOne(() => Person, 'accessId')
+  @Attr(null)
+  @IriEncoded(Person)
   declare person: Person | null
   declare person: Person | null
 
 
   @Num(0)
   @Num(0)
@@ -28,4 +29,7 @@ export default class Access extends ApiModel {
   @Attr(null)
   @Attr(null)
   @IriEncoded(Organization)
   @IriEncoded(Organization)
   declare organization: number | null
   declare organization: number | null
+
+  @Str('')
+  declare updateDate: string
 }
 }

+ 2 - 2
models/Core/Notification.ts

@@ -19,8 +19,8 @@ export default class Notification extends ApiModel {
   @Attr({})
   @Attr({})
   declare message: NotificationMessage | null
   declare message: NotificationMessage | null
 
 
-  @Str('')
-  declare createDate: string
+  @Str(null)
+  declare createDate: string | null
 
 
   @Str(null)
   @Str(null)
   declare type: string | null
   declare type: string | null

+ 53 - 0
pages/dev/poc_persist.vue

@@ -0,0 +1,53 @@
+<template>
+  <div>
+    <h1>POC Persist</h1>
+
+    <v-btn v-if="!pending" @click="onUpdateClick">Update access</v-btn>
+
+    <v-btn @click="onCreateClick">Create Notification</v-btn>
+  </div>
+</template>
+
+<script setup lang="ts">
+import { useEntityManager } from '~/composables/data/useEntityManager'
+import { useAccessProfileStore } from '~/stores/accessProfile'
+import { useEntityFetch } from '~/composables/data/useEntityFetch'
+import Access from '~/models/Access/Access'
+import Notification from '~/models/Core/Notification'
+
+definePageMeta({
+  layout: false,
+})
+
+const { em } = useEntityManager()
+
+const accessProfile = useAccessProfileStore()
+
+const accessId = accessProfile.currentAccessId
+
+const { fetch } = useEntityFetch()
+
+const { data: access, pending } = await fetch(Access, accessId)
+
+const onUpdateClick = () => {
+  if (access.value === null) {
+    throw new Error('access is null')
+  }
+
+  access.value.updateDate = new Date().toISOString()
+  console.log(access.value.id, access.value.updateDate)
+
+  em.persist(access.value)
+}
+
+
+const onCreateClick = async () => {
+  const notif = em.newInstance(Notification, { name: 'foo', message: ['bar'] })
+
+  // const notif = new Notification({ name: 'foo', message: ['bar'] })
+
+  const createdNotif = await em.persist(notif)
+
+  console.log(createdNotif)
+}
+</script>

+ 25 - 4
services/data/entityManager.ts

@@ -121,10 +121,6 @@ class EntityManager {
 
 
     const instance = repository.make(properties)
     const instance = repository.make(properties)
 
 
-    // Keep track of the model
-    // TODO : attendre de voir si utile ou non
-    // instance.setModel(model)
-
     if (
     if (
       !Object.prototype.hasOwnProperty.call(properties, 'id') ||
       !Object.prototype.hasOwnProperty.call(properties, 'id') ||
       // @ts-expect-error Si la première condition passe, on sait que id existe
       // @ts-expect-error Si la première condition passe, on sait que id existe
@@ -273,6 +269,8 @@ class EntityManager {
     let url = UrlUtils.join('api', model.entity)
     let url = UrlUtils.join('api', model.entity)
     let response
     let response
 
 
+    this.validateEntity(instance)
+
     const data: AnyJson = HydraNormalizer.normalizeEntity(instance)
     const data: AnyJson = HydraNormalizer.normalizeEntity(instance)
 
 
     const headers = { profileHash: await this.makeProfileHash() }
     const headers = { profileHash: await this.makeProfileHash() }
@@ -467,6 +465,29 @@ class EntityManager {
     const mask = this._getProfileMask()
     const mask = this._getProfileMask()
     return await ObjectUtils.hash(mask)
     return await ObjectUtils.hash(mask)
   }
   }
+
+  /**
+   * Validate the entity, and throw an error if it's not correctly defined.
+   * @param instance
+   * @protected
+   */
+  protected validateEntity(instance: unknown): void {
+    if (Object.prototype.hasOwnProperty.call(instance, 'id')) {
+      // @ts-expect-error At this point, we're sure there is an id property
+      const id = instance.id
+
+      if (
+        !(typeof id === 'number') &&
+        !(typeof id === 'string' && id.startsWith('tmp'))
+      ) {
+        // The id is a pinia orm Uid, the entity has been created using the `new` keyword (not supported for now)
+        throw new Error(
+          'Definition error for the entity, did you use the entityManager.newInstance(...) method?\n' +
+            JSON.stringify(instance),
+        )
+      }
+    }
+  }
 }
 }
 
 
 export default EntityManager
 export default EntityManager