useModels.ts 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. import { onBeforeUnmount, reactive, readonly } from "vue";
  2. import { forEachIn } from "@common/utils/forEachIn";
  3. import { useModelStore } from "@/stores/model";
  4. import Model from "@/Model";
  5. export const useModels = () => {
  6. const modelStore = useModelStore();
  7. const models = reactive({});
  8. const subscriptions = reactive({
  9. created: {},
  10. updated: {},
  11. deleted: {}
  12. });
  13. const deletedSubscriptions = reactive({});
  14. /**
  15. * Subscribes to events for when models of a certain type are created
  16. */
  17. const onCreated = async (
  18. modelName: string,
  19. callback: (data?: any) => any
  20. ) => {
  21. const subscriptionUuid = await modelStore.onCreated(
  22. modelName,
  23. callback
  24. );
  25. subscriptions.created[modelName] ??= [];
  26. subscriptions.created[modelName].push(subscriptionUuid);
  27. return subscriptionUuid;
  28. };
  29. /**
  30. * Subscribes to events for when models of a certain type are updated
  31. */
  32. const onUpdated = async (
  33. modelName: string,
  34. callback: (data?: any) => any
  35. ) => {
  36. const subscriptionUuid = await modelStore.onUpdated(
  37. modelName,
  38. callback
  39. );
  40. subscriptions.updated[modelName] ??= [];
  41. subscriptions.updated[modelName].push(subscriptionUuid);
  42. return subscriptionUuid;
  43. };
  44. /**
  45. * Subscribes to events for when models of a certain type are deleted
  46. */
  47. const onDeleted = async (
  48. modelName: string,
  49. callback: (data?: any) => any
  50. ) => {
  51. const subscriptionUuid = await modelStore.onDeleted(
  52. modelName,
  53. callback
  54. );
  55. subscriptions.deleted[modelName] ??= [];
  56. subscriptions.deleted[modelName].push(subscriptionUuid);
  57. return subscriptionUuid;
  58. };
  59. /**
  60. * Unsubscribes a specific create/update/delete subscription
  61. */
  62. const removeCallback = async (
  63. modelName: string,
  64. type: "created" | "updated" | "deleted",
  65. subscriptionUuid: string
  66. ) => {
  67. if (
  68. !subscriptions[type][modelName] ||
  69. !subscriptions[type][modelName].find(
  70. subscription => subscription === subscriptionUuid
  71. )
  72. )
  73. return;
  74. await modelStore.removeCallback(modelName, type, subscriptionUuid);
  75. delete subscriptions[type][modelName][subscriptionUuid];
  76. };
  77. /**
  78. * Sets up subscriptions to when models are deleted, to automatically remove models
  79. */
  80. const setupDeletedSubscriptions = async (modelNames: string[]) => {
  81. const modelNamesWithoutSubscriptions = modelNames.filter(
  82. modelName => !deletedSubscriptions[modelName]
  83. );
  84. await forEachIn(modelNamesWithoutSubscriptions, async modelName => {
  85. deletedSubscriptions[modelName] = await onDeleted(
  86. modelName,
  87. ({ oldDoc }) => {
  88. const { _id: modelId } = oldDoc;
  89. if (!models[modelName] || !models[modelName][modelId])
  90. return;
  91. delete models[modelName][modelId];
  92. }
  93. );
  94. });
  95. };
  96. /**
  97. * Registers a list of models, together with any potential relations
  98. */
  99. const registerModels = async (
  100. storeModels: any[],
  101. relations?: Record<string, string | string[]>
  102. ) => {
  103. const registeredModels = await modelStore.registerModels(
  104. storeModels,
  105. relations
  106. );
  107. registeredModels.forEach((model: Model) => {
  108. models[model.getName()] ??= {};
  109. models[model.getName()][model.getId()] ??= model;
  110. });
  111. const modelNames = registeredModels.reduce(
  112. (modelNames: string[], model) => {
  113. if (!modelNames.includes(model.getName()))
  114. modelNames.push(model.getName());
  115. return modelNames;
  116. },
  117. []
  118. );
  119. await setupDeletedSubscriptions(modelNames);
  120. return registeredModels;
  121. };
  122. /**
  123. * Registers a single model, together with any potential relations
  124. */
  125. const registerModel = async (
  126. storeModel: any,
  127. relations?: Record<string, string | string[]>
  128. ) => {
  129. const registeredModel = await modelStore.registerModel(
  130. storeModel,
  131. relations
  132. );
  133. models[registeredModel.getName()] ??= {};
  134. models[registeredModel.getName()][registeredModel.getId()] ??=
  135. registeredModel;
  136. await setupDeletedSubscriptions([registeredModel.getName()]);
  137. return registeredModel;
  138. };
  139. /**
  140. * Tries to load one or more models for a specific model type, along with any potential relations
  141. * Just like in registerModels, the models that are loaded are also registered
  142. */
  143. const loadModels = async (
  144. modelName: string,
  145. modelIdOrModelIds: string | string[],
  146. relations?: Record<string, string | string[]>
  147. ) => {
  148. const modelIds = Array.isArray(modelIdOrModelIds)
  149. ? modelIdOrModelIds
  150. : [modelIdOrModelIds];
  151. models[modelName] ??= {};
  152. const missingModelIds = modelIds.filter(
  153. modelId => !models[modelName][modelId]
  154. );
  155. const existingModelIds = modelIds.filter(
  156. modelId => !!models[modelName][modelId]
  157. );
  158. const existingModels = existingModelIds.map(
  159. modelId => models[modelName][modelId]
  160. );
  161. if (relations)
  162. await forEachIn(existingModels, async model =>
  163. model.loadRelations(relations)
  164. );
  165. if (existingModels.length === modelIds.length)
  166. return Object.fromEntries(
  167. existingModels.map(model => [model._id, model])
  168. );
  169. const loadedModels = await modelStore.loadModels(
  170. modelName,
  171. missingModelIds,
  172. relations
  173. );
  174. const missingModels: Model[] = Object.values(loadedModels).filter(
  175. missingModel => !!missingModel
  176. );
  177. missingModels.forEach(model => {
  178. models[modelName][model.getId()] ??= model;
  179. });
  180. const modelNames = missingModels.reduce(
  181. (modelNames: string[], model) => {
  182. if (!modelNames.includes(model.getName()))
  183. modelNames.push(model.getName());
  184. return modelNames;
  185. },
  186. []
  187. );
  188. await setupDeletedSubscriptions(modelNames);
  189. return Object.fromEntries(
  190. existingModels
  191. .concat(Object.values(missingModels))
  192. .map(model => [model._id, model])
  193. );
  194. };
  195. /**
  196. * Unregisters one or more model
  197. */
  198. const unregisterModels = async (modelName, modelIds: string[]) => {
  199. const modelIdsToUnregister = modelIds.filter(
  200. modelId => !!(models[modelName] && models[modelName][modelId])
  201. );
  202. await modelStore.unregisterModels(modelName, modelIdsToUnregister);
  203. modelIdsToUnregister.forEach(modelId => {
  204. if (!models[modelName] || !models[modelName][modelId]) return;
  205. delete models[modelName][modelId];
  206. });
  207. };
  208. /**
  209. * The below is called before the Vue component/page that created this instance of this composable is unmounted
  210. * It cleans up any models and subscriptions
  211. */
  212. onBeforeUnmount(async () => {
  213. // Before unmount, unsubscribe from all subscriptions for this composable
  214. const subscriptionTypes = Object.keys(subscriptions);
  215. await forEachIn(
  216. subscriptionTypes,
  217. async (subscriptionType: "created" | "updated" | "deleted") => {
  218. const modelNames = Object.keys(subscriptions[subscriptionType]);
  219. await forEachIn(modelNames, async modelName => {
  220. const subscriptionUuids =
  221. subscriptions[subscriptionType][modelName];
  222. await forEachIn(
  223. subscriptionUuids,
  224. async subscriptionUuid => {
  225. await removeCallback(
  226. modelName,
  227. subscriptionType,
  228. subscriptionUuid
  229. );
  230. }
  231. );
  232. });
  233. }
  234. );
  235. // Before unmount, unregister all models from this composable
  236. const modelNames = Object.keys(models);
  237. await forEachIn(modelNames, async modelName => {
  238. const modelIds = Object.keys(models[modelName]);
  239. await unregisterModels(modelName, modelIds);
  240. });
  241. });
  242. return {
  243. models: readonly(models),
  244. subscriptions: readonly(subscriptions),
  245. deletedSubscriptions: readonly(deletedSubscriptions),
  246. onCreated,
  247. onUpdated,
  248. onDeleted,
  249. removeCallback,
  250. registerModel,
  251. registerModels,
  252. unregisterModels,
  253. loadModels
  254. };
  255. };