Skip to content

Commit

Permalink
Allow a custom storage for the api caches
Browse files Browse the repository at this point in the history
  • Loading branch information
bperel committed Oct 15, 2023
1 parent 9ae4039 commit 5c5d38e
Show file tree
Hide file tree
Showing 16 changed files with 119 additions and 119 deletions.
8 changes: 5 additions & 3 deletions apps/web/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
export {
createCachedCoaApi,
createCachedUserApi,
getCommonCacheOptions,
} from "./src/api";
import { bookcase } from "./src/stores/bookcase";
import { coa } from "./src/stores/coa";
import * as apiUtil from "./src/util/api";
export const stores = {
coa,
bookcase,
};

export const util = apiUtil;

export { default as i18n } from "./src/i18n";
13 changes: 10 additions & 3 deletions apps/web/src/App.vue
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,22 @@
</template>

<script setup lang="ts">
import { buildWebStorage } from "axios-cache-interceptor";
import { coa } from "~/stores/coa";
import { collection } from "~/stores/collection";
import { cachedCoaApi } from "~/util/api";
import { coa } from "./stores/coa";
import { createCachedCoaApi } from "./api";
collection().loadUser();
onBeforeMount(() => {
coa().setApi(cachedCoaApi);
coa().setApi(
createCachedCoaApi(
buildWebStorage(sessionStorage),
import.meta.env.VITE_GATEWAY_URL,
),
);
});
</script>

Expand Down
68 changes: 68 additions & 0 deletions apps/web/src/api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import axios from "axios";
import {
CacheOptions,
CacheRequestConfig,
setupCache,
} from "axios-cache-interceptor";
import dayjs from "dayjs";

import { addUrlParamsRequestInterceptor } from "~axios-helper";

const now = dayjs();
const inAnHour = dayjs().add(1, "hour");

let coaCacheExpiration = dayjs();
if (now.get("hour") >= 4) {
coaCacheExpiration = coaCacheExpiration.add(1, "day");
}
coaCacheExpiration = coaCacheExpiration
.set("hour", 4)
.set("minute", 0)
.set("second", 0)
.set("millisecond", 0);

export const getCommonCacheOptions = (
storage: CacheOptions["storage"],
): CacheOptions => ({
etag: false,
modifiedSince: false,
interpretHeader: false,
generateKey: (options: CacheRequestConfig) =>
`${options.url}${
options.params ? `?${new URLSearchParams(options.params).toString()}` : ""
}`,
storage: storage,
});

export const createCachedCoaApi = (
storage: CacheOptions["storage"],
baseURL: string,
) =>
addUrlParamsRequestInterceptor(
setupCache(
axios.create({
baseURL,
}),
{
...getCommonCacheOptions(storage),
methods: ["get", "post"],
ttl: coaCacheExpiration.diff(now),
},
),
);

export const createCachedUserApi = (
storage: CacheOptions["storage"],
baseURL: string,
) =>
addUrlParamsRequestInterceptor(
setupCache(
axios.create({
baseURL,
}),
{
...getCommonCacheOptions(storage),
ttl: inAnHour.diff(now),
},
),
);
11 changes: 3 additions & 8 deletions apps/web/src/components/RecentEvents.vue
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@ const isCollectionUpdateEvent = (event: AbstractEvent) =>
const isEdgeCreationEvent = (event: AbstractEvent) =>
event.hasOwnProperty("edges");
const fetchEventsAndAssociatedData = async (clearCacheEntry: boolean) => {
await users().fetchEvents(clearCacheEntry);
const fetchEventsAndAssociatedData = async () => {
await users().fetchEvents();
await coa().fetchPublicationNames([
...events
Expand All @@ -63,16 +63,11 @@ const fetchEventsAndAssociatedData = async (clearCacheEntry: boolean) => {
await users().fetchStats(
eventUserIds.filter((userId) => userId !== null) as number[],
clearCacheEntry,
);
};
(async () => {
await fetchEventsAndAssociatedData(false);
setTimeout(async () => {
// await fetchEventsAndAssociatedData(true);
// hasFreshEvents = true;
}, 1000);
await fetchEventsAndAssociatedData();
isLoaded = true;
})();
</script>
Expand Down
32 changes: 10 additions & 22 deletions apps/web/src/stores/users.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,22 @@
import axios from "axios";
import { buildWebStorage } from "axios-cache-interceptor";
import { defineStore } from "pinia";

import { cachedUserApi as userApi } from "~/util/api";
import { createCachedUserApi } from "~/api";
import {
GET__events,
GET__global_stats__bookcase__contributors,
GET__global_stats__user__$userIds,
GET__global_stats__user__count,
} from "~api-routes";
import { call } from "~axios-helper";
import { BookcaseContributor } from "~dm-types/BookcaseContributor";
import { AbstractEvent } from "~dm-types/events/AbstractEvent";
import { BookstoreCommentEvent } from "~dm-types/events/BookstoreCommentEvent";
import { CollectionSubscriptionAdditionEvent } from "~dm-types/events/CollectionSubscriptionAdditionEvent";
import { CollectionUpdateEvent } from "~dm-types/events/CollectionUpdateEvent";
import { EdgeCreationEvent } from "~dm-types/events/EdgeCreationEvent";
import { SignupEvent } from "~dm-types/events/SignupEvent";

const cachedUserApi = createCachedUserApi(
buildWebStorage(sessionStorage),
import.meta.env.VITE_GATEWAY_URL,
);

export const users = defineStore("users", () => {
const count = ref(null as number | null),
Expand Down Expand Up @@ -73,26 +75,12 @@ export const users = defineStore("users", () => {
).data;
}
},
fetchEvents = async (clearCacheEntry = true) => {
const { data, cached } = await userApi.get(
"/events",
clearCacheEntry ? {} : { cache: false },
);
events.value = (
data as (
| BookstoreCommentEvent
| CollectionSubscriptionAdditionEvent
| CollectionUpdateEvent
| EdgeCreationEvent
| SignupEvent
)[]
)
fetchEvents = async () => {
events.value = (await call(cachedUserApi, new GET__events())).data
.sort(({ timestamp: timestamp1 }, { timestamp: timestamp2 }) =>
Math.sign(timestamp2 - timestamp1),
)
.filter((_, index) => index < 50);

return !cached;
};

return {
Expand Down
61 changes: 0 additions & 61 deletions apps/web/src/util/api.ts

This file was deleted.

1 change: 1 addition & 0 deletions packages/api-routes/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { CoverSearchResults } from "~dm-types/CoverSearchResults";
import { EdgeModel } from "~dm-types/EdgeModel";
import { EdgeWithModelId } from "~dm-types/EdgeWithModelId";
import { EditSubscription } from "~dm-types/EditSubscription";
import { Event } from "~dm-types/Event";
import { ImageElement } from "~dm-types/ImageElement";
import { IssueCoverDetails } from "~dm-types/IssueCoverDetails";
import { } from "~dm-types/IssueSuggestionList";
Expand Down
2 changes: 1 addition & 1 deletion packages/api/routes/bookcase/:username/options.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { ExpressCall } from "~routes/_express-call";

import { checkValidBookcaseUser } from "./index";
import { checkValidBookcaseUser } from ".";

export const get = async (
...[req, res]: ExpressCall<{
Expand Down
2 changes: 1 addition & 1 deletion packages/api/routes/bookcase/:username/sort.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import prismaDm from "~prisma-clients/extended/dm.extends";
import { ExpressCall } from "~routes/_express-call";

import { checkValidBookcaseUser } from "./index";
import { checkValidBookcaseUser } from ".";

const getLastPublicationPosition = async (userId: number) =>
(
Expand Down
2 changes: 1 addition & 1 deletion packages/api/routes/coa/list/publications/:countrycode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import bodyParser from "body-parser";
import { PublicationTitles } from "~dm-types/PublicationTitles";
import { ExpressCall } from "~routes/_express-call";

import { getPublicationTitles } from "./index";
import { getPublicationTitles } from ".";

const parseForm = bodyParser.json();

Expand Down
2 changes: 1 addition & 1 deletion packages/api/routes/coa/stories/search/withIssues.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import bodyParser from "body-parser";
import { StorySearchResults } from "~dm-types/StorySearchResults";
import { ExpressCall } from "~routes/_express-call";

import { getStoriesByKeywords } from "./index";
import { getStoriesByKeywords } from ".";

const parseForm = bodyParser.json();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { prismaDm } from "~/prisma";
import { userOptionType } from "~prisma-clients/client_dm";
import { ExpressCall } from "~routes/_express-call";

import { getIssuesForSale } from "../index";
import { getIssuesForSale } from "..";

export const get = async (
...[req, res]: ExpressCall<{
Expand Down
2 changes: 1 addition & 1 deletion packages/api/routes/collection/subscriptions/:id.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { prismaDm } from "~/prisma";
import { EditSubscription } from "~dm-types/EditSubscription";
import { ExpressCall } from "~routes/_express-call";

import { upsertSubscription } from "./index";
import { upsertSubscription } from ".";

const parseForm = bodyParser.json();

Expand Down
4 changes: 2 additions & 2 deletions packages/api/routes/events.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import dayjs from "dayjs";

import { prismaDm } from "~/prisma";
import { Event } from "~dm-types/Event";
import {
AbstractEvent,
AbstractEventRaw,
Expand All @@ -18,7 +19,6 @@ import {
EdgeCreationEvent,
EdgeCreationEventRaw,
} from "~dm-types/events/EdgeCreationEvent";
import { Event } from "~dm-types/events/Event";
import { MedalEvent } from "~dm-types/events/MedalEvent";
import { SignupEvent } from "~dm-types/events/SignupEvent";
import { ExpressCall } from "~routes/_express-call";
Expand Down Expand Up @@ -54,7 +54,7 @@ const mapUsers = <T extends AbstractEvent>(event: AbstractEventRaw): T =>
event.users?.split(",")?.map((userId) => parseInt(userId)) ||
(event.userId && [event.userId]) ||
[],
} as T);
}) as T;

const retrieveSignups = async (): Promise<SignupEvent[]> =>
(
Expand Down
14 changes: 14 additions & 0 deletions packages/types/Event.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { BookstoreCommentEvent } from "./events/BookstoreCommentEvent";
import { CollectionSubscriptionAdditionEvent } from "./events/CollectionSubscriptionAdditionEvent";
import { CollectionUpdateEvent } from "./events/CollectionUpdateEvent";
import { EdgeCreationEvent } from "./events/EdgeCreationEvent";
import { MedalEvent } from "./events/MedalEvent";
import { SignupEvent } from "./events/SignupEvent";

export type Event =
| SignupEvent
| CollectionUpdateEvent
| CollectionSubscriptionAdditionEvent
| BookstoreCommentEvent
| EdgeCreationEvent
| MedalEvent;
14 changes: 0 additions & 14 deletions packages/types/events/Event.ts

This file was deleted.

0 comments on commit 5c5d38e

Please sign in to comment.