({
data,
client,
}: CreateEntityInput<D, V>)
| 82 | } |
| 83 | |
| 84 | export function createEntity<D, V>({ |
| 85 | data, |
| 86 | client, |
| 87 | }: CreateEntityInput<D, V>): Entity<D, V> { |
| 88 | const { store } = client; |
| 89 | const { definition, db } = store; |
| 90 | |
| 91 | const { config } = definition; |
| 92 | const dataWithDefaults = fillDataDefaults(data, store); |
| 93 | |
| 94 | assertDataMatchDefinition(dataWithDefaults, definition); |
| 95 | |
| 96 | const initialKey = data[config.idField!]; |
| 97 | |
| 98 | const observableData = makeAutoObservable<D & object>( |
| 99 | dataWithDefaults as D & object, |
| 100 | config.customObservableAnnotations, |
| 101 | { |
| 102 | name: `${definition.config.name}-${initialKey}`, |
| 103 | } |
| 104 | ); |
| 105 | |
| 106 | const cleanupObject = createCleanupObject(); |
| 107 | |
| 108 | const viewLinker: EntityViewLinker<D> = { |
| 109 | db, |
| 110 | updateSelf(data) { |
| 111 | return entity.update(data) as EntityUpdatedEvent<D, unknown>; |
| 112 | }, |
| 113 | cleanup: cleanupObject, |
| 114 | }; |
| 115 | |
| 116 | const view = config.getView?.(observableData, viewLinker) ?? ({} as V); |
| 117 | |
| 118 | // Note: we dont want to add view as {...data, ...connections}. Connections might have getters so it would simply unwrap them. |
| 119 | const observableDataAndView = extendObservable( |
| 120 | observableData, |
| 121 | view as V & object |
| 122 | ); |
| 123 | |
| 124 | const entityMethods: EntityMethods<D, V> = { |
| 125 | definition, |
| 126 | db: db, |
| 127 | store: store, |
| 128 | client, |
| 129 | cleanup: cleanupObject, |
| 130 | remove() { |
| 131 | client.remove(entityMethods.getId()); |
| 132 | }, |
| 133 | isRemoved() { |
| 134 | return !store.findById(entityMethods.getId()); |
| 135 | }, |
| 136 | getId() { |
| 137 | return `${entity[config.idField!]}`; |
| 138 | }, |
| 139 | getIdPropName() { |
| 140 | return config.idField as string; |
| 141 | }, |
no test coverage detected