Skip to content

Commit

Permalink
web,api: Cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
bperel committed Aug 31, 2024
1 parent 30c7c2a commit 499387c
Show file tree
Hide file tree
Showing 12 changed files with 100 additions and 156 deletions.
3 changes: 2 additions & 1 deletion apps/web/src/App.vue
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,11 @@ getCurrentInstance()!.appContext.app.provide(
},
}),
);
console.log("provided");
const { loadUser } = collection();
const { isLoadingUser, user } = storeToRefs(collection());
loadUser();
// loadUser();
</script>

<style lang="scss">
Expand Down
2 changes: 1 addition & 1 deletion apps/web/src/components/Event.vue
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@
</template>
<template v-else-if="collectionUpdateEvent"
>&nbsp;{{ $t("a ajouté") }}&nbsp;<Issue
:issuecode="collectionUpdateEvent.issuecode"
:issuecode="collectionUpdateEvent.exampleIssuecode"
hide-condition
:flex="false"
/>
Expand Down
4 changes: 2 additions & 2 deletions apps/web/src/components/RecentEvents.vue
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ const fetchEventsAndAssociatedData = async () => {
await fetchIssuecodeDetails([
...events.value
.filter((event) => isCollectionUpdateEvent(event))
.map((event) => event.issuecode || ""),
.map(({ exampleIssuecode }) => exampleIssuecode),
...events.value
.filter((event) => isEdgeCreationEvent(event))
.reduce<
Expand All @@ -62,7 +62,7 @@ const fetchEventsAndAssociatedData = async () => {
.filter((event) => isCollectionUpdateEvent(event))
.map(
(event) =>
issuecodeDetails.value[event.issuecode].publicationcode || "",
issuecodeDetails.value[event.exampleIssuecode].publicationcode || "",
),
...events.value
.filter((event) => isEdgeCreationEvent(event))
Expand Down
8 changes: 4 additions & 4 deletions apps/web/src/composables/useDmSocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,10 +86,10 @@ const defaultExport = (
}),
coa: addNamespace<CoaServices>(CoaServices.namespaceEndpoint, {
onConnectError,
cache: {
storage: cacheStorage,
ttl: until4am(),
},
// cache: {
// storage: cacheStorage,
// ttl: until4am(),
// },
}),
globalStats: addNamespace<GlobalStatsServices>(
GlobalStatsServices.namespaceEndpoint,
Expand Down
7 changes: 4 additions & 3 deletions packages/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,10 @@ const httpServer = createServer(async (req, res) => {
res.write(JSON.stringify(data));
res.end();
});

httpServer.listen(3000);
console.log("WebSocket open on port 3000");

const io = new ServerWithUser(httpServer, {
cors: {
origin: true,
Expand All @@ -93,9 +97,6 @@ instrument(io, {
auth: false,
});

httpServer.listen(3000);
console.log("WebSocket open on port 3000");

io.use(OptionalAuthMiddleware);
io.use((_socket, next) => {
process.on("unhandledRejection", (reason: Error) => {
Expand Down
10 changes: 7 additions & 3 deletions packages/api/services/auth/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,13 @@ const AuthMiddleware = (
) => {
const token = socket.handshake.auth.token;

if (required && token == null) {
next(new Error("No token provided"));
return;
if (token == null) {
if (required) {
next(new Error("No token provided"));
return;
} else {
next();
}
}

jwt.verify(
Expand Down
1 change: 1 addition & 0 deletions packages/api/services/bookstores/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { namespaceEndpoint } from "./types";

export default (io: Server) => {
(io.of(namespaceEndpoint) as Namespace<Events>).on("connection", (socket) => {
console.log("connected to bookstores");
socket.on("getActiveBookstores", (callback) =>
prismaDm.bookstore
.findMany({
Expand Down
26 changes: 15 additions & 11 deletions packages/api/services/coa/issues/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,21 @@ import { prismaClient as prismaCoa } from "~prisma-schemas/schemas/coa/client";
import type Events from "../types";
export default (socket: Socket<Events>) => {
socket.on("getIssues", (issuecodes, callback) =>
prismaCoa.inducks_issue
.findMany({
select: {
publicationcode: true,
issuenumber: true,
issuecode: true,
},
where: { issuecode: { in: issuecodes } },
})
.then((data) => data.groupBy("issuecode"))
.then(callback),
issuecodes.length
? prismaCoa.inducks_issue
.findMany({
select: {
publicationcode: true,
issuenumber: true,
issuecode: true,
},
where: {
issuecode: { in: issuecodes.filter((issuecode) => issuecode) },
},
})
.then((data) => data.groupBy("issuecode"))
.then(callback)
: callback({}),
);

socket.on("getIssuesByPublicationcodes", async (publicationcodes, callback) =>
Expand Down
16 changes: 4 additions & 12 deletions packages/api/services/events/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ const MEDALS_L10N_FR: Record<string, string> = {
const mapUsers = <T extends AbstractEvent>(event: AbstractEventRaw): T =>
({
...event,

users:
event.users?.split(",")?.map((userId) => parseInt(userId)) ||
(event.userId && [event.userId]) ||
Expand All @@ -85,10 +86,10 @@ const retrieveCollectionUpdates = async (): Promise<CollectionUpdateEvent[]> =>
users.ID AS userId,
UNIX_TIMESTAMP(DateAjout) AS timestamp,
COUNT(Numero) AS numberOfIssues,
(SELECT CONCAT(Pays, '/', Magazine, '/', Numero)
(SELECT issuecode
FROM numeros n
WHERE n.ID = numeros.ID
LIMIT 1) AS exampleIssue
LIMIT 1) AS exampleIssuecode
FROM numeros
INNER JOIN users ON numeros.ID_Utilisateur = users.ID
WHERE DateAjout > DATE_ADD(NOW(), INTERVAL -1 MONTH)
Expand All @@ -98,16 +99,7 @@ const retrieveCollectionUpdates = async (): Promise<CollectionUpdateEvent[]> =>
GROUP BY users.ID, DATE(DateAjout)
HAVING COUNT(Numero) > 0
`
).map((event) => {
const [publicationcode, issuenumber] =
event.exampleIssue.split(/\/(?=[^/]+$)/);
return {
...mapUsers<CollectionUpdateEvent>(event),
numberOfIssues: event.numberOfIssues,
publicationcode: publicationcode || "",
issuenumber: issuenumber || "",
} as CollectionUpdateEvent;
});
).map((event) => mapUsers(event));

const retrieveCollectionSubscriptionAdditions = async (): Promise<
CollectionSubscriptionAdditionEvent[]
Expand Down
88 changes: 45 additions & 43 deletions packages/socket.io-client-services/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,10 @@ export const useSocket = (socketRootUrl: string) => ({
};
cache?: Required<SocketCacheOptions<Services>>;
} = {
onConnectError(e, namespace) {
console.error(`${namespace}: connect_error: ${e}`);
onConnectError(e, namespace) {
console.error(`${namespace}: connect_error: ${e}`);
},
},
},
) => {
const { session, onConnectError, cache } = namespaceOptions;
const socket = io(socketRootUrl + namespaceName, {
Expand All @@ -69,7 +69,9 @@ export const useSocket = (socketRootUrl: string) => ({
},
}).on("connect_error", (e) => {
onConnectError(e, namespaceName);
});
}).on('connect', () => {
console.log('connected to', namespaceName);
})

return {
socket,
Expand All @@ -79,46 +81,46 @@ export const useSocket = (socketRootUrl: string) => ({
_: never,
event: EventName,
) =>
async (
...args: AllButLast<Parameters<Services[EventName]>>
): Promise<
EventReturnTypeIncludingError<Services[EventName]> | undefined
> => {
const startTime = Date.now();
const debugCall = (post: boolean = false) =>
console.debug(
`${post ? "Called" : "Calling"} socket event`,
`${namespaceName}/${event}`,
args,
post ? `in ${Date.now() - startTime}ms` : "",
);
let cacheKey;
if (cache) {
cacheKey = `${event} ${JSON.stringify(args)}`;
const cacheData = (await cache.storage.get(cacheKey, {
cache: {
ttl:
typeof cache.ttl === "function"
? cache.ttl(event, args)
: cache.ttl,
},
})) as Awaited<ReturnType<Socket["emitWithAck"]>>;
const hasCacheData =
cacheData !== undefined &&
!(typeof cacheData === "object" && cacheData.state === "empty");
if (hasCacheData) {
console.debug("Using cache for socket event", event, args);
return cacheData;
async (
...args: AllButLast<Parameters<Services[EventName]>>
): Promise<
EventReturnTypeIncludingError<Services[EventName]> | undefined
> => {
const startTime = Date.now();
const debugCall = (post: boolean = false) =>
console.debug(
`${post ? "Called" : "Calling"} socket event`,
`${namespaceName}/${event}`,
args,
post ? `in ${Date.now() - startTime}ms` : "",
);
let cacheKey;
if (cache) {
cacheKey = `${event} ${JSON.stringify(args)}`;
const cacheData = (await cache.storage.get(cacheKey, {
cache: {
ttl:
typeof cache.ttl === "function"
? cache.ttl(event, args)
: cache.ttl,
},
})) as Awaited<ReturnType<Socket["emitWithAck"]>>;
const hasCacheData =
cacheData !== undefined &&
!(typeof cacheData === "object" && cacheData.state === "empty");
if (hasCacheData) {
console.debug("Using cache for socket event", event, args);
return cacheData;
}
}
}
debugCall();
const data = await socket.emitWithAck(event, ...args);
if (cache && cacheKey) {
cache.storage.set(cacheKey, data);
}
debugCall(true);
return data;
},
debugCall();
const data = await socket.emitWithAck(event, ...args);
if (cache && cacheKey) {
cache.storage.set(cacheKey, data);
}
debugCall(true);
return data;
},
}),
};
},
Expand Down
9 changes: 6 additions & 3 deletions packages/types/events/CollectionUpdateEvent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,16 @@ import { AbstractEvent } from "./AbstractEvent";

export class CollectionUpdateEventRaw {
type = "collection_update";
numberOfIssues = 0;
exampleIssue = "";
timestamp = 0;
numberOfIssues!: number;
userId!: number
timestamp!: number;
exampleIssuecode!: string;
issuecode!: string;
}

export class CollectionUpdateEvent extends AbstractEvent {
type = "collection_update";
numberOfIssues!: number;
exampleIssuecode!: string;
issuecode!: string;
}
Loading

0 comments on commit 499387c

Please sign in to comment.