@goatlab/fluent 0.7.3 → 0.7.4

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.
@@ -1,16 +1,20 @@
1
1
  import { Collection } from '@goatlab/js-utils';
2
2
  import { FindByIdFilter, FluentHasManyParams, FluentBelongsToParams, FluentBelongsToManyParams, FluentQuery, LogicOperator, Primitives, PrimitivesArray, QueryFieldSelector, QueryOutput, SingleQueryOutput } from './types';
3
3
  export interface FluentConnectorInterface<ModelDTO, InputDTO, OutputDTO> {
4
- findByIds<T extends FindByIdFilter<ModelDTO>>(ids: string[], q?: T): Promise<QueryOutput<T, ModelDTO, OutputDTO>>;
5
- findMany<T extends FluentQuery<ModelDTO>>(query?: T): Promise<QueryOutput<T, ModelDTO, OutputDTO>>;
6
4
  insert(data: InputDTO): Promise<OutputDTO>;
7
5
  insertMany(data: InputDTO[]): Promise<OutputDTO[]>;
6
+ findById<T extends FindByIdFilter<ModelDTO>>(id: string, q?: T): Promise<SingleQueryOutput<T, ModelDTO, OutputDTO> | null>;
7
+ findByIds<T extends FindByIdFilter<ModelDTO>>(ids: string[], q?: T): Promise<QueryOutput<T, ModelDTO, OutputDTO>>;
8
+ findMany<T extends FluentQuery<ModelDTO>>(query?: T): Promise<QueryOutput<T, ModelDTO, OutputDTO>>;
9
+ findFirst<T extends FluentQuery<ModelDTO>>(query?: T): Promise<SingleQueryOutput<T, ModelDTO, OutputDTO> | null>;
10
+ requireById(id: string, q?: FindByIdFilter<ModelDTO>): Promise<SingleQueryOutput<FindByIdFilter<ModelDTO>, ModelDTO, OutputDTO>>;
11
+ requireFirst<T extends FluentQuery<ModelDTO>>(query?: T): Promise<SingleQueryOutput<T, ModelDTO, OutputDTO>>;
12
+ updateById(id: string, data: InputDTO): Promise<OutputDTO>;
13
+ replaceById(id: string, data: InputDTO): Promise<OutputDTO>;
14
+ deleteById(id: string): Promise<string>;
8
15
  loadFirst(query?: FluentQuery<ModelDTO>): any;
9
16
  loadById(id: string): any;
10
- replaceById(id: string, data: InputDTO): Promise<OutputDTO>;
11
- updateById(id: string, data: InputDTO): Promise<OutputDTO>;
12
- clear(): Promise<boolean>;
13
- requireById(id: string, q?: FindByIdFilter<ModelDTO>): Promise<SingleQueryOutput<FindByIdFilter<ModelDTO>, ModelDTO, OutputDTO>>;
17
+ raw(): any;
14
18
  }
15
19
  export declare abstract class BaseConnector<ModelDTO, InputDTO, OutputDTO> {
16
20
  protected outputKeys: string[];
@@ -28,11 +32,14 @@ export declare abstract class BaseConnector<ModelDTO, InputDTO, OutputDTO> {
28
32
  protected modelRelations: any;
29
33
  isMongoDB: boolean;
30
34
  constructor();
31
- findByIds<T extends FindByIdFilter<ModelDTO>>(ids: string[], q?: T): Promise<QueryOutput<T, ModelDTO, OutputDTO>>;
32
35
  insertMany(data: InputDTO[]): Promise<OutputDTO[]>;
33
36
  updateById(id: string, data: InputDTO): Promise<OutputDTO>;
34
37
  findMany<T extends FluentQuery<ModelDTO>>(query?: T): Promise<QueryOutput<T, ModelDTO, OutputDTO>>;
35
38
  findFirst<T extends FluentQuery<ModelDTO>>(query?: T): Promise<SingleQueryOutput<T, ModelDTO, OutputDTO> | null>;
39
+ requireById(id: string, q?: FindByIdFilter<ModelDTO>): Promise<SingleQueryOutput<FindByIdFilter<ModelDTO>, ModelDTO, OutputDTO>>;
40
+ requireFirst<T extends FluentQuery<ModelDTO>>(query?: T): Promise<SingleQueryOutput<T, ModelDTO, OutputDTO>>;
41
+ findByIds<T extends FindByIdFilter<ModelDTO>>(ids: string[], q?: T): Promise<QueryOutput<T, ModelDTO, OutputDTO>>;
42
+ findById<T extends FindByIdFilter<ModelDTO>>(id: string, q?: T): Promise<SingleQueryOutput<T, ModelDTO, OutputDTO> | null>;
36
43
  collect(query: FluentQuery<ModelDTO>): Promise<Collection<OutputDTO>>;
37
44
  pluck(path: QueryFieldSelector<ModelDTO>, query?: FluentQuery<ModelDTO>): Promise<Primitives[]>;
38
45
  protected setRelatedQuery(r: {
@@ -16,9 +16,6 @@ class BaseConnector {
16
16
  this.rawQuery = undefined;
17
17
  this.outputKeys = [];
18
18
  }
19
- async findByIds(ids, q) {
20
- throw new Error('findByIds() method not implemented');
21
- }
22
19
  async insertMany(data) {
23
20
  throw new Error('get() method not implemented');
24
21
  }
@@ -35,6 +32,57 @@ class BaseConnector {
35
32
  }
36
33
  return data[0];
37
34
  }
35
+ async requireById(id, q) {
36
+ const found = await this.findByIds([id], {
37
+ select: q?.select,
38
+ include: q?.include,
39
+ limit: 1
40
+ });
41
+ found.map(d => {
42
+ if (this.isMongoDB) {
43
+ d['id'] = d['id'].toString();
44
+ }
45
+ this.clearEmpties(js_utils_1.Objects.deleteNulls(d));
46
+ });
47
+ if (!found[0]) {
48
+ throw new Error(`Object ${id} not found`);
49
+ }
50
+ return found[0];
51
+ }
52
+ async requireFirst(query) {
53
+ const found = await this.findMany({ ...query, limit: 1 });
54
+ found.map(d => {
55
+ if (this.isMongoDB) {
56
+ d['id'] = d['id'].toString();
57
+ }
58
+ this.clearEmpties(js_utils_1.Objects.deleteNulls(d));
59
+ });
60
+ if (!found[0]) {
61
+ const stringQuery = query ? JSON.stringify(query) : '';
62
+ throw new Error(`No objects found matching: ${stringQuery}`);
63
+ }
64
+ return found[0];
65
+ }
66
+ async findByIds(ids, q) {
67
+ let data = await this.findMany({
68
+ where: {
69
+ id: {
70
+ in: ids
71
+ }
72
+ },
73
+ limit: q?.limit,
74
+ select: q?.select,
75
+ include: q?.include
76
+ });
77
+ return data;
78
+ }
79
+ async findById(id, q) {
80
+ const result = await this.findByIds([id], { ...q, limit: 1 });
81
+ if (!result[0]) {
82
+ return null;
83
+ }
84
+ return result[0];
85
+ }
38
86
  async collect(query) {
39
87
  const data = await this.findMany(query);
40
88
  if (!Array.isArray(data)) {
@@ -1,4 +1,4 @@
1
- import { FindByIdFilter, LoadedResult, QueryOutput, SingleQueryOutput } from './../types';
1
+ import { LoadedResult, QueryOutput } from './../types';
2
2
  import { FindManyOptions, Repository, MongoRepository } from 'typeorm';
3
3
  import { BaseConnector, FluentConnectorInterface } from '../BaseConnector';
4
4
  import type { AnyObject, FluentQuery } from '../types';
@@ -22,22 +22,21 @@ export declare class TypeOrmConnector<ModelDTO = AnyObject, InputDTO = ModelDTO,
22
22
  constructor({ entity, dataSource, inputSchema, outputSchema }: TypeOrmConnectorParams<InputDTO, OutputDTO>);
23
23
  insert(data: InputDTO): Promise<OutputDTO>;
24
24
  insertMany(data: InputDTO[]): Promise<OutputDTO[]>;
25
+ findMany<T extends FluentQuery<ModelDTO>>(query?: T): Promise<QueryOutput<T, ModelDTO, OutputDTO>>;
26
+ updateById(id: string, data: InputDTO): Promise<OutputDTO>;
27
+ replaceById(id: string, data: InputDTO): Promise<OutputDTO>;
28
+ deleteById(id: string): Promise<string>;
29
+ clear(): Promise<boolean>;
30
+ loadFirst(query?: FluentQuery<ModelDTO>): LoadedResult<this>;
31
+ loadById(id: string): LoadedResult<this>;
25
32
  raw(): Repository<ModelDTO>;
26
33
  mongoRaw(): MongoRepository<ModelDTO>;
27
- findMany<T extends FluentQuery<ModelDTO>>(query?: T): Promise<QueryOutput<T, ModelDTO, OutputDTO>>;
34
+ protected clone(): any;
35
+ private getOrderBy;
28
36
  private getMongoSelect;
29
37
  private getMongoLookup;
30
38
  private customMongoRelatedSearch;
31
39
  private generateTypeOrmQuery;
32
40
  protected getTypeOrmWhere(where?: FluentQuery<ModelDTO>['where']): FindManyOptions['where'];
33
41
  protected getTypeOrmMongoWhere(where?: FluentQuery<ModelDTO>['where']): FindManyOptions['where'];
34
- updateById(id: string, data: InputDTO): Promise<OutputDTO>;
35
- replaceById(id: string, data: InputDTO): Promise<OutputDTO>;
36
- clear(): Promise<boolean>;
37
- loadFirst(query?: FluentQuery<ModelDTO>): TypeOrmConnector<ModelDTO, InputDTO, OutputDTO>;
38
- loadById(id: string): LoadedResult<this>;
39
- requireById(id: string, q?: FindByIdFilter<ModelDTO>): Promise<SingleQueryOutput<FindByIdFilter<ModelDTO>, ModelDTO, OutputDTO>>;
40
- protected clone(): any;
41
- findByIds<T extends FindByIdFilter<ModelDTO>>(ids: string[], q?: T): Promise<QueryOutput<T, ModelDTO, OutputDTO>>;
42
- private getOrderBy;
43
42
  }
@@ -69,12 +69,6 @@ class TypeOrmConnector extends BaseConnector_1.BaseConnector {
69
69
  return this.clearEmpties(js_utils_1.Objects.deleteNulls(d));
70
70
  }));
71
71
  }
72
- raw() {
73
- return this.repository;
74
- }
75
- mongoRaw() {
76
- return this.repository;
77
- }
78
72
  async findMany(query) {
79
73
  if (this.isMongoDB && query?.include) {
80
74
  const mongoRelationResult = this.customMongoRelatedSearch(query);
@@ -108,6 +102,131 @@ class TypeOrmConnector extends BaseConnector_1.BaseConnector {
108
102
  }
109
103
  return this.outputSchema?.array().parse(found);
110
104
  }
105
+ async updateById(id, data) {
106
+ const parsedId = this.isMongoDB
107
+ ? js_utils_1.Ids.objectID(id)
108
+ : id;
109
+ const idFieldName = this.isMongoDB ? '_id' : 'id';
110
+ const dataToInsert = this.outputKeys.includes('updated')
111
+ ? {
112
+ ...data,
113
+ ...{ updated: new Date() }
114
+ }
115
+ : data;
116
+ const validatedData = this.inputSchema.parse(dataToInsert);
117
+ const updateResults = await this.repository.update(id, validatedData);
118
+ if (updateResults.affected === 0) {
119
+ throw new Error('No rows where affected');
120
+ }
121
+ const dbResult = await this.repository.findOneOrFail({
122
+ where: {
123
+ [idFieldName]: parsedId
124
+ }
125
+ });
126
+ if (this.isMongoDB) {
127
+ dbResult['id'] = dbResult['id'].toString();
128
+ }
129
+ return this.outputSchema?.parse(this.clearEmpties(js_utils_1.Objects.deleteNulls(dbResult)));
130
+ }
131
+ async replaceById(id, data) {
132
+ const parsedId = this.isMongoDB
133
+ ? js_utils_1.Ids.objectID(id)
134
+ : id;
135
+ const idFieldName = this.isMongoDB ? '_id' : 'id';
136
+ const value = await this.repository.findOneOrFail({
137
+ where: {
138
+ [idFieldName]: parsedId
139
+ }
140
+ });
141
+ const flatValue = js_utils_1.Objects.flatten(JSON.parse(JSON.stringify(value)));
142
+ Object.keys(flatValue).forEach(key => {
143
+ flatValue[key] = null;
144
+ });
145
+ const nullObject = js_utils_1.Objects.nest(flatValue);
146
+ const newValue = { ...nullObject, ...data };
147
+ delete newValue._id;
148
+ delete newValue.id;
149
+ delete newValue.created;
150
+ delete newValue.updated;
151
+ const dataToInsert = this.outputKeys.includes('updated')
152
+ ? {
153
+ ...data,
154
+ ...{ updated: new Date() }
155
+ }
156
+ : data;
157
+ const validatedData = this.inputSchema.parse(dataToInsert);
158
+ const updateResults = await this.repository.update(id, validatedData);
159
+ if (updateResults.affected === 0) {
160
+ throw new Error('No rows where affected');
161
+ }
162
+ const val = await this.repository.findOneOrFail({
163
+ where: {
164
+ [idFieldName]: parsedId
165
+ }
166
+ });
167
+ if (this.isMongoDB) {
168
+ val['id'] = val['id'].toString();
169
+ }
170
+ return this.outputSchema.parse(this.clearEmpties(js_utils_1.Objects.deleteNulls(val)));
171
+ }
172
+ async deleteById(id) {
173
+ const parsedId = this.isMongoDB
174
+ ? js_utils_1.Ids.objectID(id)
175
+ : id;
176
+ await this.repository.delete(parsedId);
177
+ return id;
178
+ }
179
+ async clear() {
180
+ await this.repository.clear();
181
+ return true;
182
+ }
183
+ loadFirst(query) {
184
+ const newInstance = this.clone();
185
+ newInstance.setRelatedQuery({
186
+ entity: this.entity,
187
+ repository: this,
188
+ query: {
189
+ ...query,
190
+ limit: 1
191
+ }
192
+ });
193
+ return newInstance;
194
+ }
195
+ loadById(id) {
196
+ const newInstance = this.clone();
197
+ newInstance.setRelatedQuery({
198
+ entity: this.entity,
199
+ repository: this,
200
+ query: {
201
+ where: {
202
+ id
203
+ }
204
+ }
205
+ });
206
+ return newInstance;
207
+ }
208
+ raw() {
209
+ return this.repository;
210
+ }
211
+ mongoRaw() {
212
+ return this.repository;
213
+ }
214
+ clone() {
215
+ return new this.constructor();
216
+ }
217
+ getOrderBy(orderBy) {
218
+ if (!orderBy || orderBy.length === 0) {
219
+ return {};
220
+ }
221
+ const order = {};
222
+ for (const orderElement of orderBy) {
223
+ const flattenOrder = js_utils_1.Objects.flatten(orderElement);
224
+ for (const k of Object.keys(flattenOrder)) {
225
+ order[k] = flattenOrder[k];
226
+ }
227
+ }
228
+ return js_utils_1.Objects.nest(order);
229
+ }
111
230
  getMongoSelect(select) {
112
231
  const selected = js_utils_1.Objects.flatten(select || {});
113
232
  for (const k of Object.keys(selected)) {
@@ -268,7 +387,15 @@ class TypeOrmConnector extends BaseConnector_1.BaseConnector {
268
387
  filter.take = query.paginated.perPage;
269
388
  filter.skip = (query.paginated?.page - 1) * query?.paginated.perPage;
270
389
  }
271
- filter.select = js_utils_1.Objects.flatten(query?.select || {});
390
+ if (query?.select) {
391
+ const selectQuery = js_utils_1.Objects.flatten(query?.select || {});
392
+ if (this.isMongoDB) {
393
+ filter.select = Object.keys(selectQuery);
394
+ }
395
+ else {
396
+ filter.select = selectQuery;
397
+ }
398
+ }
272
399
  filter.order = this.getOrderBy(query?.orderBy);
273
400
  filter.relations = query?.include;
274
401
  return filter;
@@ -629,144 +756,5 @@ class TypeOrmConnector extends BaseConnector_1.BaseConnector {
629
756
  const filtered = this.clearEmpties(Filters.where);
630
757
  return filtered;
631
758
  }
632
- async updateById(id, data) {
633
- const parsedId = this.isMongoDB
634
- ? js_utils_1.Ids.objectID(id)
635
- : id;
636
- const idFieldName = this.isMongoDB ? '_id' : 'id';
637
- const dataToInsert = this.outputKeys.includes('updated')
638
- ? {
639
- ...data,
640
- ...{ updated: new Date() }
641
- }
642
- : data;
643
- const validatedData = this.inputSchema.parse(dataToInsert);
644
- const updateResults = await this.repository.update(id, validatedData);
645
- if (updateResults.affected === 0) {
646
- throw new Error('No rows where affected');
647
- }
648
- const dbResult = await this.repository.findOneOrFail({
649
- where: {
650
- [idFieldName]: parsedId
651
- }
652
- });
653
- if (this.isMongoDB) {
654
- dbResult['id'] = dbResult['id'].toString();
655
- }
656
- return this.outputSchema?.parse(this.clearEmpties(js_utils_1.Objects.deleteNulls(dbResult)));
657
- }
658
- async replaceById(id, data) {
659
- const parsedId = this.isMongoDB
660
- ? js_utils_1.Ids.objectID(id)
661
- : id;
662
- const idFieldName = this.isMongoDB ? '_id' : 'id';
663
- const value = await this.repository.findOneOrFail({
664
- where: {
665
- [idFieldName]: parsedId
666
- }
667
- });
668
- const flatValue = js_utils_1.Objects.flatten(JSON.parse(JSON.stringify(value)));
669
- Object.keys(flatValue).forEach(key => {
670
- flatValue[key] = null;
671
- });
672
- const nullObject = js_utils_1.Objects.nest(flatValue);
673
- const newValue = { ...nullObject, ...data };
674
- delete newValue._id;
675
- delete newValue.id;
676
- delete newValue.created;
677
- delete newValue.updated;
678
- const dataToInsert = this.outputKeys.includes('updated')
679
- ? {
680
- ...data,
681
- ...{ updated: new Date() }
682
- }
683
- : data;
684
- const validatedData = this.inputSchema.parse(dataToInsert);
685
- const updateResults = await this.repository.update(id, validatedData);
686
- if (updateResults.affected === 0) {
687
- throw new Error('No rows where affected');
688
- }
689
- const val = await this.repository.findOneOrFail({
690
- where: {
691
- [idFieldName]: parsedId
692
- }
693
- });
694
- if (this.isMongoDB) {
695
- val['id'] = val['id'].toString();
696
- }
697
- return this.outputSchema.parse(this.clearEmpties(js_utils_1.Objects.deleteNulls(val)));
698
- }
699
- async clear() {
700
- await this.repository.clear();
701
- return true;
702
- }
703
- loadFirst(query) {
704
- const detachedClass = Object.assign(Object.create(Object.getPrototypeOf(this)), this);
705
- detachedClass.setRelatedQuery({
706
- entity: this.entity,
707
- repository: this,
708
- query
709
- });
710
- return detachedClass;
711
- }
712
- loadById(id) {
713
- const newInstance = this.clone();
714
- newInstance.setRelatedQuery({
715
- entity: this.entity,
716
- repository: this,
717
- query: {
718
- where: {
719
- id
720
- }
721
- }
722
- });
723
- return newInstance;
724
- }
725
- async requireById(id, q) {
726
- const found = await this.findByIds([id], {
727
- select: q?.select,
728
- include: q?.include,
729
- limit: 1
730
- });
731
- found.map(d => {
732
- if (this.isMongoDB) {
733
- d['id'] = d['id'].toString();
734
- }
735
- this.clearEmpties(js_utils_1.Objects.deleteNulls(d));
736
- });
737
- if (!found[0]) {
738
- throw new Error(`Object ${id} not found`);
739
- }
740
- return this.outputSchema?.parse(found[0]);
741
- }
742
- clone() {
743
- return new this.constructor();
744
- }
745
- async findByIds(ids, q) {
746
- let data = await this.findMany({
747
- where: {
748
- id: {
749
- in: ids
750
- }
751
- },
752
- limit: q?.limit,
753
- select: q?.select,
754
- include: q?.include
755
- });
756
- return this.outputSchema?.array().parse(data);
757
- }
758
- getOrderBy(orderBy) {
759
- if (!orderBy || orderBy.length === 0) {
760
- return {};
761
- }
762
- const order = {};
763
- for (const orderElement of orderBy) {
764
- const flattenOrder = js_utils_1.Objects.flatten(orderElement);
765
- for (const k of Object.keys(flattenOrder)) {
766
- order[k] = flattenOrder[k];
767
- }
768
- }
769
- return js_utils_1.Objects.nest(order);
770
- }
771
759
  }
772
760
  exports.TypeOrmConnector = TypeOrmConnector;
@@ -1 +1 @@
1
- export declare const basicTestSuite: (Repository: any) => void;
1
+ export declare const basicTestSuite: (Repo: any) => void;
@@ -1,23 +1,63 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.basicTestSuite = void 0;
4
+ const js_utils_1 = require("@goatlab/js-utils");
4
5
  const flock_1 = require("../flock");
5
- const basicTestSuite = Repository => {
6
+ const basicTestSuite = Repo => {
6
7
  let storedId;
8
+ let Repository;
7
9
  beforeAll(() => {
8
- Repository = new Repository();
10
+ Repository = new Repo();
9
11
  });
10
- test('Insert - Should insert data', async () => {
12
+ test('insert - Should insert data', async () => {
11
13
  const a = await Repository.insert({ name: 'myGoat', age: 13 });
12
14
  expect(typeof a.id).toBe('string');
13
15
  expect(a.name).toBe('myGoat');
14
16
  expect(0).toBe(0);
15
17
  });
16
- it('Create Multiple - Should insert Multiple elements', async () => {
18
+ it('insertMany - Should insert Multiple elements', async () => {
17
19
  const insertedFlock = await Repository.insertMany(flock_1.flock);
18
20
  expect(insertedFlock[0].name).toBe('Goatee');
19
21
  storedId = insertedFlock[0].id;
20
22
  });
23
+ test('findById - Should GET an object by its ID', async () => {
24
+ const goats = await Repository.insertMany(flock_1.flock);
25
+ const goat = await Repository.findById(goats[0].id);
26
+ expect(goat?.id).toBe(goats[0].id);
27
+ expect(typeof goat?.id).toBe('string');
28
+ const anotherGoat = await Repository.findById('507f1f77bcf86cd799439011');
29
+ expect(anotherGoat).toBe(null);
30
+ });
31
+ test('findById - Should GET selected Data', async () => {
32
+ const goats = await Repository.insertMany(flock_1.flock);
33
+ const goat = await Repository.findById(goats[0].id, {
34
+ select: {
35
+ age: true
36
+ }
37
+ });
38
+ expect(goat).not.toHaveProperty('name');
39
+ expect(goat?.age).toBe(goats[0].age);
40
+ });
41
+ test('findByIds - Should GET data', async () => {
42
+ const goats = await Repository.insertMany(flock_1.flock);
43
+ const ids = [goats[0].id, goats[1].id];
44
+ const selectedGoats = await Repository.findByIds(ids);
45
+ expect(selectedGoats.length).toBe(2);
46
+ expect(selectedGoats[0].id === ids[0] || selectedGoats[1].id === ids[0]).toBe(true);
47
+ });
48
+ test('findByIds - Should GET selectedData', async () => {
49
+ const goats = await Repository.insertMany(flock_1.flock);
50
+ const ids = [goats[0].id, goats[1].id];
51
+ const ages = [goats[0].age, goats[1].age];
52
+ const selectedGoats = await Repository.findByIds(ids, {
53
+ select: {
54
+ age: true
55
+ }
56
+ });
57
+ expect(selectedGoats.length).toBe(2);
58
+ expect(selectedGoats[0].age === ages[0] || selectedGoats[1].age === ages[0]).toBe(true);
59
+ expect(selectedGoats[0]).not.toHaveProperty('name');
60
+ });
21
61
  test('findMany - Should GET data', async () => {
22
62
  await Repository.insertMany(flock_1.flock);
23
63
  const storedGoats = await Repository.findMany();
@@ -47,6 +87,69 @@ const basicTestSuite = Repository => {
47
87
  expect(Array.isArray(storedGoats)).toBe(true);
48
88
  expect(storedGoats.length).toBe(0);
49
89
  });
90
+ test('findMany - Should SELECT attributes', async () => {
91
+ await Repository.insertMany(flock_1.flock);
92
+ const storedGoats = await Repository.findMany({
93
+ where: {
94
+ name: 'Goatee'
95
+ },
96
+ select: {
97
+ age: true
98
+ }
99
+ });
100
+ expect(Array.isArray(storedGoats)).toBe(true);
101
+ expect(storedGoats.length > 0).toBe(true);
102
+ expect(storedGoats[0]).not.toHaveProperty('name');
103
+ });
104
+ test('findFirst - Should get only 1 object back', async () => {
105
+ await Repository.insertMany(flock_1.flock);
106
+ const storedGoats = await Repository.findFirst({
107
+ where: {
108
+ name: 'Goatee'
109
+ }
110
+ });
111
+ expect(Array.isArray(storedGoats)).toBe(false);
112
+ expect(typeof storedGoats.id).toBe('string');
113
+ });
114
+ test('findFirst - Should FILTER AND SELECT DATA', async () => {
115
+ await Repository.insertMany(flock_1.flock);
116
+ const storedGoats = await Repository.findFirst({
117
+ where: {
118
+ name: 'Goatee'
119
+ },
120
+ select: {
121
+ name: true
122
+ }
123
+ });
124
+ expect(Array.isArray(storedGoats)).toBe(false);
125
+ expect(storedGoats.name).toBe('Goatee');
126
+ expect(storedGoats).not.toHaveProperty('age');
127
+ });
128
+ test('requireFirst - Should fail if not found', async () => {
129
+ const insertedUser = await Repository.insert({
130
+ name: 'testGoat',
131
+ age: 20
132
+ });
133
+ const [error] = await js_utils_1.Promises.try(Repository.requireFirst({
134
+ where: {
135
+ name: 'noneExistingGoat'
136
+ }
137
+ }));
138
+ expect(error?.message).toBe('No objects found matching: {"where":{"name":"noneExistingGoat"}}');
139
+ });
140
+ test('requireFirst - Should find first item', async () => {
141
+ const insertedUser = await Repository.insert({
142
+ name: 'testGoat',
143
+ age: 20
144
+ });
145
+ const [error, goat] = await js_utils_1.Promises.try(Repository.requireFirst({
146
+ where: {
147
+ name: 'testGoat'
148
+ }
149
+ }));
150
+ expect(error).toBe(null);
151
+ expect(goat.name).toBe(insertedUser.name);
152
+ });
50
153
  it('UpdateById - Should Update a single element', async () => {
51
154
  await Repository.insertMany(flock_1.flock);
52
155
  const goats = await Repository.findMany();
@@ -67,5 +170,14 @@ const basicTestSuite = Repository => {
67
170
  expect(data.name).toBe('MyReplacedGoat');
68
171
  expect(data.id).toBe(goats[0].id);
69
172
  });
173
+ it('deleteById - Should delete an item', async () => {
174
+ await Repository.insertMany(flock_1.flock);
175
+ const goats = await Repository.findMany();
176
+ const foundGoat = await Repository.requireById(goats[0].id);
177
+ expect(foundGoat.id).toBe(goats[0].id);
178
+ await Repository.deleteById(foundGoat.id);
179
+ const [error] = await js_utils_1.Promises.try(Repository.requireById(goats[0].id));
180
+ expect(error?.message).toBe(`Object ${goats[0].id} not found`);
181
+ });
70
182
  };
71
183
  exports.basicTestSuite = basicTestSuite;