Skip to content

Commit

Permalink
feat: add peek resolution for findRecord ops
Browse files Browse the repository at this point in the history
  • Loading branch information
runspired committed Aug 23, 2024
1 parent cc8d7f9 commit e31a705
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 6 deletions.
4 changes: 2 additions & 2 deletions app/data-worker/data-worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@ import type { CacheCapabilitiesManager } from '@ember-data/store/types';
import { CachePolicy } from '@ember-data/request-utils';
import { SchemaService } from '@warp-drive/schema-record/schema';
import { register } from '../schemas/pokemon';
import { JsonSuffixHandler } from '../utils/handlers';
import { PokemonHandler } from '../utils/handlers';

class WorkerStore extends Store {
requestManager = new RequestManager()
.use([JsonSuffixHandler, Fetch])
.use([PokemonHandler, Fetch])
.useCache(CacheHandler);

lifetimes = new CachePolicy({
Expand Down
36 changes: 33 additions & 3 deletions app/utils/handlers.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,43 @@
import type { Handler, NextFn, RequestContext } from '@ember-data/request';
import type { Handler, NextFn } from '@ember-data/request';
import type { StoreRequestContext } from '@ember-data/store';

export const JsonSuffixHandler: Handler = {
async request<T>(context: RequestContext, next: NextFn<T>) {
export const PokemonHandler: Handler = {
async request<T>(context: StoreRequestContext, next: NextFn<T>) {
const { request } = context;

if (request.url?.endsWith('.json')) {
return next(request);
}

// in the findRecord case, we can check the cache first
// since our individual finds are always the same data as
// we get from list endpoints.
if (request.op === 'findRecord') {
const { store } = context.request;
const identifier = store.identifierCache.getOrCreateDocumentIdentifier(
context.request,
);
const peeked = identifier ? store.cache.peekRequest(identifier) : null;

if (!peeked) {
const identifier = request.records?.[0];
const record = identifier ? store.cache.peek(identifier) : null;

if (record) {
const headers = new Headers();
headers.set('date', new Date().toUTCString());
const response = new Response(null, {
headers,
});
context.setResponse(response);

return {
data: record,
} as T;
}
}
}

const updatedRequest = Object.assign({}, request, {
url: request.url + '.json',
});
Expand Down
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
// layout, which is not resolvable with the Node resolution algorithm, to
// work with TypeScript.
"baseUrl": ".",
"lib": ["es2022"],
"lib": ["es2022", "dom"],
"paths": {
"ember-polaris-pokedex/tests/*": [
"tests/*"
Expand Down

0 comments on commit e31a705

Please sign in to comment.