Skip to content

Commit

Permalink
Merge pull request #252 from litespace-org/moehab/rmv-cache-rules
Browse files Browse the repository at this point in the history
removed(models): rules from the cache; and its corresponding uses across the code base.
  • Loading branch information
neuodev authored Dec 26, 2024
2 parents abb481b + 0f92068 commit f0bf6f2
Show file tree
Hide file tree
Showing 12 changed files with 26 additions and 333 deletions.
3 changes: 1 addition & 2 deletions packages/luna/src/locales/ar-eg.json
Original file line number Diff line number Diff line change
Expand Up @@ -494,7 +494,6 @@
"student-dashboard.overview.total-lessons": "اجمالي الحصص",
"student-dashboard.overview.completed-lessons": "الحصص المكتملة",
"student-dashboard.overview.total-learning-time": "اجمالي وقت التعلم",
"student-dashboard.overview.total-learning-time.unit.hour": "{value} س",
"student-dashboard.overview.total-learning-time.unit.minute": "{value} د",
"student-dashboard.overview.teachers": "عدد المعلمين",
"student-dashboard.loading": "برجاء الانتظار... جاري تحميل بيانات لوحتك الرئيسية!",
Expand Down Expand Up @@ -718,4 +717,4 @@
"error.password.short": "رقم سري قصير",
"error.password.long": "رقم سري طويل",
"error.password.invalid": "يجب أن يحتوي علي أرقام، حروف ، رموز"
}
}
3 changes: 0 additions & 3 deletions packages/models/src/cache/index.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
import { createClient } from "redis";
import { Tutors } from "@/cache/tutors";
import { Rules } from "@/cache/rules";
import { RedisClient } from "@/cache/base";
import { Peer } from "@/cache/peer";
import { Call } from "@/cache/call";
import { OnlineStatus } from "@/cache/onlineStatus";

export class Cache {
public tutors: Tutors;
public rules: Rules;
public peer: Peer;
public call: Call;
public onlineStatus: OnlineStatus;
Expand All @@ -18,7 +16,6 @@ export class Cache {
const client = createClient({ url });
this.client = client;
this.tutors = new Tutors(client);
this.rules = new Rules(client);
this.peer = new Peer(client);
this.call = new Call(client);
this.onlineStatus = new OnlineStatus(client);
Expand Down
85 changes: 0 additions & 85 deletions packages/models/src/cache/rules.ts

This file was deleted.

73 changes: 0 additions & 73 deletions packages/models/tests/cache/rule.test.ts

This file was deleted.

6 changes: 0 additions & 6 deletions packages/types/src/rule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,12 +97,6 @@ export type FindUserRulesWithSlotsApiResponse = {
slots: Slot[];
};

export type Cache = {
tutor: number;
rule: number;
events: RuleEvent[];
};

/**
* Slot: represents unpacked time slot at specific time and duration.
*
Expand Down
2 changes: 1 addition & 1 deletion packages/types/src/tutor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ export type FindTutorInfoApiResponse = {

export type FindOnboardedTutorsApiResponse = {
total: number;
list: Array<Cache & { rules: IRule.RuleEvent[] }>;
list: Array<Cache>;
};

export type PublicTutorFieldsForStudio = {
Expand Down
6 changes: 1 addition & 5 deletions services/server/src/handlers/lesson.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ import { safe } from "@litespace/sol/error";
import { unpackRules } from "@litespace/sol/rule";
import { isAdmin, isStudent, isUser } from "@litespace/auth";
import { platformConfig } from "@/constants";
import { cache } from "@/lib/cache";
import dayjs from "@/lib/dayjs";
import { canBook } from "@/lib/call";
import { concat, isEqual } from "lodash";
Expand Down Expand Up @@ -124,8 +123,6 @@ function create(context: ApiContext) {
}),
};

await cache.rules.setOne(payload);

context.io.sockets
.in(Wss.Room.TutorsCache)
.emit(Wss.ServerEvent.LessonBooked, payload);
Expand Down Expand Up @@ -253,8 +250,7 @@ function cancel(context: ApiContext) {
slots,
}),
};
// update tutor rules cache
await cache.rules.setOne(payload);

// notify client
context.io.sockets
.to(Wss.Room.TutorsCache)
Expand Down
49 changes: 3 additions & 46 deletions services/server/src/handlers/rule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,8 @@ import {
asSlots,
unpackRules,
} from "@litespace/sol/rule";
import { safe } from "@litespace/sol/error";
import { isEmpty } from "lodash";
import { ApiContext } from "@/types/api";
import { cache } from "@/lib/cache";
import dayjs from "@/lib/dayjs";
import { isTutorManager, isTutor, isUser } from "@litespace/auth";
import { isOnboard } from "@/lib/tutor";
Expand Down Expand Up @@ -86,22 +84,7 @@ function createRule(context: ApiContext) {
}
const rule = await rules.create({ ...payload, userId: user.id });
res.status(201).json(rule);

const error = await safe(async () => {
const today = dayjs.utc().startOf("day");
await cache.rules.setOne({
tutor: rule.userId,
rule: rule.id,
events: unpackRules({
rules: [rule],
slots: [],
start: today.toISOString(),
end: today.add(30, "days").toISOString(),
}),
});
context.io.to(Wss.Room.TutorsCache).emit(Wss.ServerEvent.RuleCreated);
});
if (error instanceof Error) console.log(error);
context.io.to(Wss.Room.TutorsCache).emit(Wss.ServerEvent.RuleCreated);
}
);
}
Expand Down Expand Up @@ -256,28 +239,7 @@ function updateRule(context: ApiContext) {
activated: payload.activated,
});
res.status(200).json(updatedRule);

const error = await safe(async () => {
const today = dayjs.utc().startOf("day");
const ruleLessons = await lessons.find({
rules: [rule.id],
canceled: false,
full: true,
});

await cache.rules.setOne({
tutor: rule.userId,
rule: rule.id,
events: unpackRules({
rules: [rule],
slots: asSlots(ruleLessons.list),
start: today.toISOString(),
end: today.add(30, "days").toISOString(),
}),
});
context.io.to(Wss.Room.TutorsCache).emit(Wss.ServerEvent.RuleUpdated);
});
if (error instanceof Error) console.log(error);
context.io.to(Wss.Room.TutorsCache).emit(Wss.ServerEvent.RuleUpdated);
}
);
}
Expand Down Expand Up @@ -308,12 +270,7 @@ function deleteRule(context: ApiContext) {
: await rules.update(ruleId, { deleted: true });

res.status(204).json(deletedRule);

const error = await safe(async () => {
await cache.rules.deleteOne({ tutor: rule.userId, rule: rule.id });
context.io.to(Wss.Room.TutorsCache).emit(Wss.ServerEvent.RuleDeleted);
});
if (error instanceof Error) console.log(error);
context.io.to(Wss.Room.TutorsCache).emit(Wss.ServerEvent.RuleDeleted);
}
);
}
Expand Down
27 changes: 9 additions & 18 deletions services/server/src/handlers/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,6 @@ import { cache } from "@/lib/cache";
import { sendBackgroundMessage } from "@/workers";
import { WorkerMessageType } from "@/workers/messages";
import { isValidPassword } from "@litespace/sol/verification";
import { selectTutorRuleEvents } from "@/lib/events";
import { isTutor, isTutorManager } from "@litespace/auth/dist/authorization";

const createUserPayload = zod.object({
Expand Down Expand Up @@ -391,21 +390,13 @@ async function findOnboardedTutors(req: Request, res: Response) {
const query: ITutor.FindOnboardedTutorsParams =
findOnboardedTutorsQuery.parse(req.query);

const [isTutorsCached, isRulesCached] = await Promise.all([
cache.tutors.exists(),
cache.rules.exists(),
]);

const validCacheState = isTutorsCached && isRulesCached;
const isTutorsCached = await cache.tutors.exists();

// retrieve/set tutors and rules from/in cache (redis)
const { tutors, rules } = validCacheState
? {
tutors: await cache.tutors.getAll(),
rules: await cache.rules.getAll(),
}
: // DONE: Update the tutors cache according to the new design in (@/architecture/v1.0/tutors.md)
await cacheTutors(dayjs.utc().startOf("day"));
const tutorsCache = isTutorsCached
? await cache.tutors.getAll()
// DONE: Update the tutors cache according to the new design in (@/architecture/v1.0/tutors.md)
: await cacheTutors();

// order tutors based on time of the first event, genger of the user
// online state, and notice.
Expand All @@ -414,17 +405,17 @@ async function findOnboardedTutors(req: Request, res: Response) {
isUser(user) && user.gender ? (user.gender as IUser.Gender) : undefined;

const filtered = query.search
? tutors.filter((tutor) => {
? tutorsCache.filter((tutor) => {
if (!query.search) return true;
const regex = new RegExp(query.search, "gi");
const nameMatch = tutor.name && regex.test(tutor.name);
const topicMatch = tutor.topics.find((topic) => regex.test(topic));
return nameMatch || topicMatch;
})
: tutors;
: tutorsCache;

const ordered = orderTutors({
tutors: filtered,
rules,
userGender,
});

Expand All @@ -439,7 +430,7 @@ async function findOnboardedTutors(req: Request, res: Response) {
// ITutor.FindOnboardedTutorsApiResponse list attribute
const list = paginated.map((tutor) => ({
...tutor,
rules: selectTutorRuleEvents(rules, tutor),
slots: [] // TODO: retrieve AvailabilitySlots from the db
}));

// DONE: Update the response to match the new design in (@/architecture/v1.0/tutors.md)
Expand Down
Loading

0 comments on commit f0bf6f2

Please sign in to comment.