@declaro/data 2.0.0-beta.116 → 2.0.0-beta.117

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.
@@ -5,6 +5,7 @@ import { MockBookSchema, type MockBookInput } from '../../test/mock/models/mock-
5
5
  import { EventManager } from '@declaro/core'
6
6
  import { mock } from 'bun:test'
7
7
  import type { InferDetail } from '../../shared/utils/schema-inference'
8
+ import { ModelMutationAction } from '../events/event-types'
8
9
 
9
10
  describe('ModelService', () => {
10
11
  const namespace = 'books'
@@ -629,432 +630,4 @@ describe('ModelService', () => {
629
630
  expect(results).toEqual(inputs)
630
631
  })
631
632
  })
632
-
633
- describe('normalizeInput functionality', () => {
634
- class TestModelService extends ModelService<typeof mockSchema> {
635
- public testNormalizeInput(input: any) {
636
- return this.normalizeInput(input)
637
- }
638
-
639
- protected async normalizeInput(input: MockBookInput): Promise<MockBookInput> {
640
- return {
641
- ...input,
642
- title: input.title?.trim(),
643
- author: input.author?.trim(),
644
- publishedDate: new Date('2023-01-01'),
645
- }
646
- }
647
- }
648
-
649
- let testService: TestModelService
650
-
651
- beforeEach(() => {
652
- testService = new TestModelService({ repository, emitter, schema: mockSchema, namespace })
653
- })
654
-
655
- it('should use default normalizeInput method (no changes) when not overridden', async () => {
656
- const input = { title: ' Test Book ', author: ' Author Name ', publishedDate: new Date() }
657
- const normalized = await service['normalizeInput'](input)
658
-
659
- expect(normalized).toEqual(input)
660
- expect(normalized).toBe(input) // Should be the exact same reference
661
- })
662
-
663
- it('should use custom normalizeInput method for create operation', async () => {
664
- const input = { title: ' Test Book ', author: ' Author Name ', publishedDate: new Date() }
665
- const createdItem = await testService.create(input)
666
-
667
- expect(createdItem.title).toBe('Test Book')
668
- expect(createdItem.author).toBe('Author Name')
669
- expect(createdItem.publishedDate).toEqual(new Date('2023-01-01'))
670
- })
671
-
672
- it('should use custom normalizeInput method for update operation', async () => {
673
- const input = { id: 42, title: 'Original Book', author: 'Original Author', publishedDate: new Date() }
674
- const createdItem = await testService.create(input)
675
-
676
- const updateInput = { title: ' Updated Book ', author: ' Updated Author ', publishedDate: new Date() }
677
- const updatedItem = await testService.update({ id: createdItem.id }, updateInput)
678
-
679
- expect(updatedItem.title).toBe('Updated Book')
680
- expect(updatedItem.author).toBe('Updated Author')
681
- expect(updatedItem.publishedDate).toEqual(new Date('2023-01-01'))
682
- })
683
-
684
- it('should use custom normalizeInput method for upsert operation', async () => {
685
- const input = { id: 42, title: ' Test Book ', author: ' Author Name ', publishedDate: new Date() }
686
- const upsertedItem = await testService.upsert(input)
687
-
688
- expect(upsertedItem.title).toBe('Test Book')
689
- expect(upsertedItem.author).toBe('Author Name')
690
- expect(upsertedItem.publishedDate).toEqual(new Date('2023-01-01'))
691
-
692
- // Upsert again with different data
693
- const updateInput = {
694
- id: 42,
695
- title: ' Updated Book ',
696
- author: ' Updated Author ',
697
- publishedDate: new Date(),
698
- }
699
- const updatedItem = await testService.upsert(updateInput)
700
-
701
- expect(updatedItem.title).toBe('Updated Book')
702
- expect(updatedItem.author).toBe('Updated Author')
703
- expect(updatedItem.publishedDate).toEqual(new Date('2023-01-01'))
704
- })
705
-
706
- it('should use custom normalizeInput method for bulkUpsert operation', async () => {
707
- const inputs = [
708
- { id: 1, title: ' Book One ', author: ' Author One ', publishedDate: new Date() },
709
- { id: 2, title: ' Book Two ', author: ' Author Two ', publishedDate: new Date() },
710
- { title: ' Book Three ', author: ' Author Three ', publishedDate: new Date() }, // No ID - will be created
711
- ]
712
-
713
- const results = await testService.bulkUpsert(inputs)
714
-
715
- expect(results).toHaveLength(3)
716
- expect(results[0].title).toBe('Book One')
717
- expect(results[0].author).toBe('Author One')
718
- expect(results[0].publishedDate).toEqual(new Date('2023-01-01'))
719
-
720
- expect(results[1].title).toBe('Book Two')
721
- expect(results[1].author).toBe('Author Two')
722
- expect(results[1].publishedDate).toEqual(new Date('2023-01-01'))
723
-
724
- expect(results[2].title).toBe('Book Three')
725
- expect(results[2].author).toBe('Author Three')
726
- expect(results[2].publishedDate).toEqual(new Date('2023-01-01'))
727
- })
728
-
729
- it('should preserve events order with normalized input in create operation', async () => {
730
- const input = { title: ' Test Book ', author: ' Author Name ', publishedDate: new Date() }
731
- await testService.create(input)
732
-
733
- // Debug: Let's see what was actually called
734
- const beforeCreateCall = beforeCreateSpy.mock.calls[0][0]
735
- const afterCreateCall = afterCreateSpy.mock.calls[0][0]
736
-
737
- expect(beforeCreateCall.meta.input.title).toBe('Test Book')
738
- expect(beforeCreateCall.meta.input.author).toBe('Author Name')
739
- expect(beforeCreateCall.meta.input.publishedDate).toEqual(new Date('2023-01-01'))
740
-
741
- expect(afterCreateCall.meta.input.title).toBe('Test Book')
742
- expect(afterCreateCall.meta.input.author).toBe('Author Name')
743
- expect(afterCreateCall.meta.input.publishedDate).toEqual(new Date('2023-01-01'))
744
- })
745
-
746
- it('should call normalizeInput method exactly once per input during bulkUpsert with Promise.all', async () => {
747
- const normalizeInputSpy = mock(async (input: any) => ({ ...input, normalized: true }))
748
-
749
- class SpyService extends ModelService<typeof mockSchema> {
750
- protected async normalizeInput(input: any) {
751
- return normalizeInputSpy(input)
752
- }
753
- }
754
-
755
- const spyService = new SpyService({ repository, emitter, schema: mockSchema, namespace })
756
-
757
- const inputs = [
758
- { id: 1, title: 'Book One', author: 'Author One', publishedDate: new Date() },
759
- { id: 2, title: 'Book Two', author: 'Author Two', publishedDate: new Date() },
760
- ]
761
-
762
- await spyService.bulkUpsert(inputs)
763
-
764
- expect(normalizeInputSpy).toHaveBeenCalledTimes(2)
765
- expect(normalizeInputSpy).toHaveBeenNthCalledWith(1, inputs[0])
766
- expect(normalizeInputSpy).toHaveBeenNthCalledWith(2, inputs[1])
767
- })
768
-
769
- it('should handle async normalization errors gracefully', async () => {
770
- class ErrorNormalizationService extends ModelService<typeof mockSchema> {
771
- protected async normalizeInput(input: any) {
772
- if (input.title === 'ERROR') {
773
- throw new Error('Normalization failed')
774
- }
775
- return input
776
- }
777
- }
778
-
779
- const errorService = new ErrorNormalizationService({
780
- repository,
781
- emitter,
782
- schema: mockSchema,
783
- namespace,
784
- })
785
-
786
- const input = { title: 'ERROR', author: 'Author Name', publishedDate: new Date() }
787
-
788
- await expect(errorService.create(input)).rejects.toThrow('Normalization failed')
789
- })
790
-
791
- it('should process bulk normalization in parallel for performance', async () => {
792
- const processingTimes: number[] = []
793
-
794
- class TimingNormalizationService extends ModelService<typeof mockSchema> {
795
- protected async normalizeInput(input: any) {
796
- const start = Date.now()
797
- // Simulate some async work
798
- await new Promise((resolve) => setTimeout(resolve, 50))
799
- processingTimes.push(Date.now() - start)
800
- return input
801
- }
802
- }
803
-
804
- const timingService = new TimingNormalizationService({
805
- repository,
806
- emitter,
807
- schema: mockSchema,
808
- namespace,
809
- })
810
-
811
- const inputs = [
812
- { id: 1, title: 'Book One', author: 'Author One', publishedDate: new Date() },
813
- { id: 2, title: 'Book Two', author: 'Author Two', publishedDate: new Date() },
814
- { id: 3, title: 'Book Three', author: 'Author Three', publishedDate: new Date() },
815
- ]
816
-
817
- const start = Date.now()
818
- await timingService.bulkUpsert(inputs)
819
- const totalTime = Date.now() - start
820
-
821
- // With Promise.all, total time should be closer to single operation time rather than sum of all
822
- // Allow some variance for test stability
823
- expect(totalTime).toBeLessThan(150) // Much less than 3 * 50ms = 150ms
824
- expect(processingTimes).toHaveLength(3)
825
- })
826
- })
827
-
828
- describe('Response Normalization', () => {
829
- class TestRepository extends MockMemoryRepository<typeof mockSchema> {
830
- constructor() {
831
- super({
832
- schema: mockSchema,
833
- })
834
- }
835
-
836
- async create(input: MockBookInput): Promise<any> {
837
- const record = await super.create(input)
838
- // Return with publishedDate as string to test normalization
839
- record.publishedDate = '2024-01-01' as any
840
- return record
841
- }
842
-
843
- async update(lookup: any, input: MockBookInput): Promise<any> {
844
- const record = await super.update(lookup, input)
845
- // Return with publishedDate as string to test normalization
846
- record.publishedDate = '2024-01-01' as any
847
- return record
848
- }
849
-
850
- async upsert(input: MockBookInput): Promise<any> {
851
- const record = await super.upsert(input)
852
- // Return with publishedDate as string to test normalization
853
- record.publishedDate = '2024-01-01' as any
854
- return record
855
- }
856
-
857
- async bulkUpsert(inputs: MockBookInput[]): Promise<any[]> {
858
- const records = await super.bulkUpsert(inputs)
859
- // Return with publishedDate as string to test normalization
860
- for (const record of records) {
861
- record.publishedDate = '2024-01-01' as any
862
- }
863
- return records
864
- }
865
-
866
- async remove(lookup: any): Promise<any> {
867
- const record = await super.remove(lookup)
868
- // Return with publishedDate as string to test normalization
869
- if (record) {
870
- record.publishedDate = '2024-01-01' as any
871
- }
872
- return record
873
- }
874
-
875
- async restore(lookup: any): Promise<any> {
876
- const record = await super.restore(lookup)
877
- // Return with publishedDate as string to test normalization
878
- if (record) {
879
- record.publishedDate = '2024-01-01' as any
880
- }
881
- return record
882
- }
883
- }
884
-
885
- class TestServiceWithNormalization extends ModelService<typeof mockSchema> {
886
- async normalizeDetail(detail: InferDetail<typeof mockSchema>): Promise<InferDetail<typeof mockSchema>> {
887
- // Handle null case (e.g., when load returns null)
888
- if (!detail) return detail
889
-
890
- // Convert string dates back to Date objects
891
- if (typeof detail.publishedDate === 'string') {
892
- detail.publishedDate = new Date(detail.publishedDate) as any
893
- }
894
- return detail
895
- }
896
-
897
- async normalizeSummary(summary: InferDetail<typeof mockSchema>): Promise<InferDetail<typeof mockSchema>> {
898
- // Handle null case (e.g., when load returns null)
899
- if (!summary) return summary
900
-
901
- // Convert string dates back to Date objects
902
- if (typeof summary.publishedDate === 'string') {
903
- summary.publishedDate = new Date(summary.publishedDate) as any
904
- }
905
- return summary
906
- }
907
- }
908
-
909
- let testRepository: TestRepository
910
- let testService: TestServiceWithNormalization
911
-
912
- beforeEach(() => {
913
- testRepository = new TestRepository()
914
- emitter = new EventManager()
915
-
916
- testService = new TestServiceWithNormalization({
917
- repository: testRepository,
918
- emitter,
919
- schema: mockSchema,
920
- namespace,
921
- })
922
- })
923
-
924
- it('should allow custom normalization of details in the create response when overridden', async () => {
925
- const input = { id: 200, title: 'Create Test', author: 'Creator', publishedDate: new Date() }
926
- const record = await testService.create(input)
927
-
928
- const expectedDate = new Date('2024-01-01')
929
- const actualDate = record.publishedDate
930
-
931
- expect(actualDate).toEqual(expectedDate)
932
- expect(actualDate).toBeInstanceOf(Date)
933
- })
934
-
935
- it('should allow custom normalization of details in the update response when overridden', async () => {
936
- const input = { id: 201, title: 'Update Test', author: 'Updater', publishedDate: new Date() }
937
- await testRepository.create(input)
938
-
939
- const updatedInput = { title: 'Updated Test', author: 'Updated Author', publishedDate: new Date() }
940
- const record = await testService.update({ id: 201 }, updatedInput)
941
-
942
- const expectedDate = new Date('2024-01-01')
943
- const actualDate = record.publishedDate
944
-
945
- expect(actualDate).toEqual(expectedDate)
946
- expect(actualDate).toBeInstanceOf(Date)
947
- })
948
-
949
- it('should allow custom normalization of details in the upsert response when creating and overridden', async () => {
950
- const input = { id: 202, title: 'Upsert Create Test', author: 'Upserter', publishedDate: new Date() }
951
- const record = await testService.upsert(input)
952
-
953
- const expectedDate = new Date('2024-01-01')
954
- const actualDate = record.publishedDate
955
-
956
- expect(actualDate).toEqual(expectedDate)
957
- expect(actualDate).toBeInstanceOf(Date)
958
- })
959
-
960
- it('should allow custom normalization of details in the upsert response when updating and overridden', async () => {
961
- const input = { id: 203, title: 'Upsert Update Test', author: 'Upserter', publishedDate: new Date() }
962
- await testRepository.create(input)
963
-
964
- const updatedInput = {
965
- id: 203,
966
- title: 'Updated Upsert Test',
967
- author: 'Updated Upserter',
968
- publishedDate: new Date(),
969
- }
970
- const record = await testService.upsert(updatedInput)
971
-
972
- const expectedDate = new Date('2024-01-01')
973
- const actualDate = record.publishedDate
974
-
975
- expect(actualDate).toEqual(expectedDate)
976
- expect(actualDate).toBeInstanceOf(Date)
977
- })
978
-
979
- it('should allow custom normalization of details in the bulkUpsert response when overridden', async () => {
980
- const input1 = { id: 204, title: 'Bulk Test 1', author: 'Bulk Author 1', publishedDate: new Date() }
981
- const input2 = { id: 205, title: 'Bulk Test 2', author: 'Bulk Author 2', publishedDate: new Date() }
982
-
983
- const records = await testService.bulkUpsert([input1, input2])
984
-
985
- const expectedDate = new Date('2024-01-01')
986
-
987
- for (const record of records) {
988
- const actualDate = record.publishedDate
989
- expect(actualDate).toEqual(expectedDate)
990
- expect(actualDate).toBeInstanceOf(Date)
991
- }
992
- })
993
-
994
- it('should allow custom normalization of details in the bulkUpsert response with mixed create and update when overridden', async () => {
995
- const existingInput = { id: 206, title: 'Existing', author: 'Existing Author', publishedDate: new Date() }
996
- await testRepository.create(existingInput)
997
-
998
- const updateInput = {
999
- id: 206,
1000
- title: 'Updated Existing',
1001
- author: 'Updated Author',
1002
- publishedDate: new Date(),
1003
- }
1004
- const createInput = { id: 207, title: 'New Record', author: 'New Author', publishedDate: new Date() }
1005
-
1006
- const records = await testService.bulkUpsert([updateInput, createInput])
1007
-
1008
- const expectedDate = new Date('2024-01-01')
1009
-
1010
- for (const record of records) {
1011
- const actualDate = record.publishedDate
1012
- expect(actualDate).toEqual(expectedDate)
1013
- expect(actualDate).toBeInstanceOf(Date)
1014
- }
1015
- })
1016
-
1017
- it('should allow custom normalization of summaries in the remove response when overridden', async () => {
1018
- const input = { id: 208, title: 'Remove Test', author: 'Remover', publishedDate: new Date() }
1019
- await testRepository.create(input)
1020
-
1021
- const record = await testService.remove({ id: 208 })
1022
-
1023
- const expectedDate = new Date('2024-01-01')
1024
- const actualDate = record.publishedDate
1025
-
1026
- expect(actualDate).toEqual(expectedDate)
1027
- expect(actualDate).toBeInstanceOf(Date)
1028
- })
1029
-
1030
- it('should allow custom normalization of summaries in the restore response when overridden', async () => {
1031
- const input = { id: 209, title: 'Restore Test', author: 'Restorer', publishedDate: new Date() }
1032
- await testRepository.create(input)
1033
- await testRepository.remove({ id: 209 })
1034
-
1035
- const record = await testService.restore({ id: 209 })
1036
-
1037
- const expectedDate = new Date('2024-01-01')
1038
- const actualDate = record.publishedDate
1039
-
1040
- expect(actualDate).toEqual(expectedDate)
1041
- expect(actualDate).toBeInstanceOf(Date)
1042
- })
1043
-
1044
- it('should not normalize data by default when normalization methods are not overridden', async () => {
1045
- const defaultService = new ModelService({
1046
- repository: testRepository,
1047
- emitter,
1048
- schema: mockSchema,
1049
- namespace,
1050
- })
1051
-
1052
- const input = { id: 210, title: 'Default Test', author: 'Default Author', publishedDate: new Date() }
1053
- const record = await defaultService.create(input)
1054
-
1055
- // Should return the raw string from repository since no normalization is applied
1056
- expect(record.publishedDate as any).toBe('2024-01-01')
1057
- expect(typeof record.publishedDate).toBe('string')
1058
- })
1059
- })
1060
633
  })