Skip to content

Commit

Permalink
Merge branch 'main' of https://github.com/MiaadTeam/lesan
Browse files Browse the repository at this point in the history
  • Loading branch information
Serpico1899 committed Nov 12, 2023
2 parents ca47077 + c377519 commit 87706f3
Show file tree
Hide file tree
Showing 3 changed files with 207 additions and 14 deletions.
84 changes: 72 additions & 12 deletions src/odm/relation/addRelation.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { Database, ObjectId } from "../../deps.ts";
import { Db, ObjectId } from "../../npmDeps.ts";
import { createProjection } from "../../models/createProjection.ts";
import { IRelationsFileds, schemaFns, TSchemas } from "../../models/mod.ts";
import { throwError } from "../../utils/throwError.ts";
import { Projection } from "../aggregation/type.ts";
import { TInsertRelations } from "../insert/insertOne.ts";
import { handleMultiRelation } from "../utils/insert/handleMultiRelation.ts";
import { handleSingleRelation } from "../utils/insert/handleSingleRelation.ts";
import { generateRemoveRelatedRelationFilter } from "../utils/generateRemoveRelationRelationFilter.ts";
import { filterDocByProjection } from "../utils/filterDocByProjection.ts";

export const addRelation = async <TR extends IRelationsFileds>({
db,
Expand All @@ -16,7 +18,7 @@ export const addRelation = async <TR extends IRelationsFileds>({
projection,
replace,
}: {
db: Database;
db: Db;
schemasObj: TSchemas;
collection: string;
_id: ObjectId;
Expand Down Expand Up @@ -57,6 +59,68 @@ export const addRelation = async <TR extends IRelationsFileds>({
`the ${rel} relation is already added if you want to replaced this please add replace option`,
);
}
// first remove previus relatedRelation
for (
const relatedRel in foundedSchema.relations[rel]
.relatedRelations
) {
const relatedRelation =
foundedSchema.relations[rel].relatedRelations[relatedRel];

if (
relations[rel]?.relatedRelations &&
relations[rel]?.relatedRelations![relatedRel]
) {
const updateFilterForRemoveRelatedRelation =
await generateRemoveRelatedRelationFilter({
db,
relatedRelation,
removeDoc: filterDocByProjection(
foundedDoc,
pureDocProjection,
),
relatedRel,
mainSchemaName: collection,
mainSchemaRelationName: rel,
relatedRelSchemaName: foundedSchema.relations[rel].schemaName,
prevRelationDoc: foundedDoc[rel],
pureMainProjection: foundedDocPureProjection,
});

if (updateFilterForRemoveRelatedRelation.length > 0) {
const updatedRel = await db.collection(
foundedSchema.relations[rel].schemaName,
).updateOne(
{
_id: foundedDoc[rel]._id,
},
updateFilterForRemoveRelatedRelation,
);

// console.log woth no truncate
// await Deno.stdout.write(
// new TextEncoder().encode(
// `inside if with this relation: => ${
// JSON.stringify(relations, null, 2)
// }\n relationName: => ${rel}\n relatedRelSchemaName: => ${
// foundedSchema.relations[rel].schemaName
// }\n updateFileterForRemove: => ${
// JSON.stringify(updatedRel, null, 2)
// } \n with this updated doc: => ${
// JSON.stringify(foundedDoc[rel], null, 2)
// } \n with this update aggregation: => ${
// JSON.stringify(
// updateFilterForRemoveRelatedRelation,
// null,
// 2,
// )
// }
// \n`,
// ),
// );
}
}
}
await handleSingleRelation({
db,
relations,
Expand All @@ -65,12 +129,6 @@ export const addRelation = async <TR extends IRelationsFileds>({
pureRelProjection,
pureDocProjection,
generatedDoc,
replace,
});
console.log("in handle single relation : ", {
generatedDoc,
rel,
foundedRel: generatedDoc[rel],
});
await db.collection(collection).updateOne({ _id: foundedDoc._id }, {
$set: { [rel]: generatedDoc[rel] },
Expand All @@ -85,14 +143,16 @@ export const addRelation = async <TR extends IRelationsFileds>({
pureDocProjection,
generatedDoc,
});
await db.collection(collection).updateOne({ _id: foundedDoc._id }, {
$addToSet: { [rel]: { $each: generatedDoc[rel] } },
});
}

await db.collection(collection).updateOne({ _id: foundedDoc._id }, {
$addToSet: { [rel]: { $each: generatedDoc[rel] } },
});
}
}
} else {
throwError("can not find this document");
}
return projection
? await db.collection(collection).findOne({ _id }, { projection })
: { _id: foundedDoc!._id };
};
135 changes: 135 additions & 0 deletions src/odm/utils/generateRemoveRelationRelationFilter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
import { TRelatedRelation } from "../../mod.ts";
import { Db, Document, ObjectId, UpdateFilter } from "../../npmDeps.ts";
import { throwError } from "../../utils/throwError.ts";

export const generateRemoveRelatedRelationFilter = async (
{
db,
relatedRelation,
relatedRel,
removeDoc,
relatedRelSchemaName,
mainSchemaName,
prevRelationDoc,
mainSchemaRelationName,
pureMainProjection,
}: {
db: Db;
relatedRelation: TRelatedRelation;
relatedRel: string;
removeDoc: Document;
relatedRelSchemaName: string;
mainSchemaName: string;
mainSchemaRelationName: string;
prevRelationDoc: Document;
pureMainProjection: Record<string, any>;
},
) => {
let updateFilter: UpdateFilter<Document>;
if (relatedRelation.type === "single") {
updateFilter = { $set: { [relatedRel]: {} } };
} else {
updateFilter = [];

if (relatedRelation.limit) {
if (!relatedRelation.sort) {
throwError("You related relation is incorrect please add sort field");
}
const foundedRelatedRel = await db.collection(relatedRelSchemaName)
.findOne({
_id: prevRelationDoc._id,
});

if (!foundedRelatedRel) {
throwError("can not find this related relation");
}

const relatedRelDoc = foundedRelatedRel![relatedRel];

const reachedLimit = relatedRelDoc.length === relatedRelation.limit
? true
: false;

const indexOfFoundedRelatedRel = relatedRelDoc.findIndex((
rr: any,
) => rr._id.equals(removeDoc._id));

if (indexOfFoundedRelatedRel > -1) {
updateFilter.push(
{
$set: {
[relatedRel]: {
$filter: {
input: `$${relatedRel}`,
as: `${relatedRel}Item`,
cond: {
$ne: [
`$$${relatedRel}Item._id`,
removeDoc._id,
],
},
},
},
},
},
// {
// $set: {
// [relatedRel]: newRelatedRelArr,
// },
// },
);

if (reachedLimit) {
const fieldName = relatedRelation.sort!.field;
const operator = relatedRelation.sort?.order === "asc"
? { $gt: relatedRelDoc[relatedRelDoc.length - 1][fieldName] }
: { $lt: relatedRelDoc[relatedRelDoc.length - 1][fieldName] };

const findNextRelatedRelForAdd = await db.collection(mainSchemaName)
.findOne({
[`${mainSchemaRelationName}._id`]: foundedRelatedRel!._id,
[fieldName]: operator,
}, {
projection: pureMainProjection,
});

if (findNextRelatedRelForAdd) {
updateFilter.push(
{
$set: {
[relatedRel]: {
$concatArrays: [
[findNextRelatedRelForAdd],
`$${relatedRel}`,
],
},
},
},
{
$set: {
[relatedRel]: {
$sortArray: {
input: `$${relatedRel}`,
sortBy: {
[relatedRelation.sort!.field]:
relatedRelation.sort?.order === "asc" ? 1 : -1,
},
},
},
},
},
// {
// $set: {
// [relatedRel]: {
// $slice: [`$${relatedRel}`, relatedRelation.limit],
// },
// },
// },
);
}
}
}
}
}
return updateFilter;
};
2 changes: 0 additions & 2 deletions src/odm/utils/insert/handleSingleRelation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ export const handleSingleRelation = async <TR extends IRelationsFileds>({
pureDocProjection,
pureRelProjection,
generatedDoc,
replace,
}: {
db: Db;
relations: TInsertRelations<TR>;
Expand All @@ -23,7 +22,6 @@ export const handleSingleRelation = async <TR extends IRelationsFileds>({
pureRelProjection: Record<string, any>;
pureDocProjection: Record<string, any>;
generatedDoc: Record<string, any>;
replace?: boolean;
}) => {
const pureGeneratedDoc = filterDocByProjection(
generatedDoc,
Expand Down

0 comments on commit 87706f3

Please sign in to comment.