Skip to content

Commit

Permalink
fix(worker): use the cached timestamp
Browse files Browse the repository at this point in the history
  • Loading branch information
yjl9903 committed Aug 11, 2023
1 parent 541b52c commit fbcbd9c
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 15 deletions.
22 changes: 13 additions & 9 deletions packages/worker/src/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,12 @@ export const PrefetchFilter = [

export const findResourcesFromDB = memoAsync(
async (env: Env, options: ResolvedFilterOptions) => {
const prisma = makePrisma(env);

const timer = createTimer(`Search Resources`);
timer.start();

const prisma = makePrisma(env);
const timestampPromise = getRefreshTimestamp(env);

const {
page,
pageSize,
Expand Down Expand Up @@ -119,8 +120,13 @@ export const findResourcesFromDB = memoAsync(
}
});

const timestamp = await timestampPromise;
timer.end();
return result;

return {
timestamp,
resources: result
};
},
{
external: {
Expand All @@ -147,20 +153,18 @@ export async function searchResources(ctx: Context<{ Bindings: Env }>) {
return ctx.json({ message: 'Request is not valid' }, 400);
}

const timestampPromise = getRefreshTimestamp(ctx.env);

const result = !isNoCache(ctx)
const { timestamp, resources: result } = !isNoCache(ctx)
? await findResourcesFromDB(ctx.env, filter)
: await findResourcesFromDB.raw(ctx.env, filter);

const complete = result.length > filter.pageSize;
const resources = resolveQueryResult(result.slice(0, filter.pageSize));

return ctx.json({
resources,
complete,
filter,
timestamp: await timestampPromise
complete,
timestamp,
resources
});
}

Expand Down
16 changes: 10 additions & 6 deletions packages/worker/src/state.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { Resource, Team, User } from '@prisma/client/edge';
import type { ResourceDetail } from 'animegarden';
import type { Resource, Team, User } from '@prisma/client/edge';

import type { Env } from './types';

Expand All @@ -18,12 +18,13 @@ export function getDetailStore(env: Env) {
}

export function getResourcesStore(env: Env) {
return new KVStore<
(Resource & {
return new KVStore<{
timestamp: Date;
resources: (Resource & {
fansub: Team | null;
publisher: User;
})[]
>(env.animegarden, 'resources');
})[];
}>(env.animegarden, 'resources');
}

export class KVStore<V> {
Expand All @@ -34,7 +35,10 @@ export class KVStore<V> {
*/
private readonly ttl: number = 60 * 60;

constructor(private readonly store: KVNamespace, prefix = '') {
constructor(
private readonly store: KVNamespace,
prefix = ''
) {
this.prefix = prefix + ':';
}

Expand Down

0 comments on commit fbcbd9c

Please sign in to comment.