Skip to content

Commit 975c72d

Browse files
committed
feat: add createMany function to subjects service
1 parent 6e54aa2 commit 975c72d

1 file changed

Lines changed: 37 additions & 0 deletions

File tree

apps/api/src/subjects/subjects.service.ts

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,43 @@ export class SubjectsService {
4141
});
4242
}
4343

44+
async createMany(data: CreateSubjectDto[]) {
45+
//filter out all duplicate ids that are planned to be created
46+
47+
const seen = new Set();
48+
const noDuplicateSubjectsList = data.filter((record) => {
49+
if (!seen.has(record.id)) {
50+
seen.add(record.id);
51+
return true;
52+
}
53+
return false;
54+
});
55+
56+
const subjectIds = noDuplicateSubjectsList.map((record) => record.id);
57+
58+
//find the list of subject ids that already exist
59+
const existingSubjects = await this.subjectModel.findMany({
60+
select: { id: true },
61+
where: {
62+
id: { in: subjectIds }
63+
}
64+
});
65+
66+
//create a set of existing ids in the database to filter our to-be-created ids with
67+
const existingIds = new Set(existingSubjects.map((subj) => subj.id));
68+
69+
//Filter out records whose IDs already exist
70+
const subjectsToCreate = noDuplicateSubjectsList.filter((record) => !existingIds.has(record.id));
71+
72+
//if there are none left to create do not follow through with the command
73+
if (subjectsToCreate.length < 1) {
74+
return subjectsToCreate;
75+
}
76+
return this.subjectModel.createMany({
77+
data: subjectsToCreate
78+
});
79+
}
80+
4481
async deleteById(id: string, { ability }: EntityOperationOptions = {}) {
4582
const subject = await this.findById(id);
4683
return this.subjectModel.delete({

0 commit comments

Comments
 (0)