Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Queries, Queryable, and useQuery #2921

Merged
merged 1 commit into from
Mar 6, 2024
Merged

feat: Queries, Queryable, and useQuery #2921

merged 1 commit into from
Mar 6, 2024

Conversation

ntucker
Copy link
Collaborator

@ntucker ntucker commented Jan 9, 2024

Motivation

  • Reduce API footprint
    • Reduce bundle size
    • Easier to learn
    • Less code to write
  • Writing getOptimisticResponse() and other concepts based on state are significantly cleaner
  • eliminates the need to refer to endpoints or resources in endpoint arguments (which caused a lot of typing challenges)

Solution

Mechanism

Schemas now have Args - this can be used to get possible args in useQuery()

Examples

class User extends Entity {
  id = '';
  username = '';

  pk() { return this.id;}
  static indexes = ['username'] as const;
}

Before

const UserIndex = new Index(User)

const bob = useCache(UserIndex, { username: 'bob' });

After

const bob = useQuery(User, { username: 'bob' });

Before

const getUserCount = new Query(
  new schema.All(User),
  (entries, { isAdmin } = { }) => {
    if (isAdmin !== undefined)
      return entries.filter(user => user.isAdmin === isAdmin).length;
    return entries.length;
  },
);

const userCount = useCache(getUserCount);
const adminCount = useCache(getUserCount, { isAdmin: true });

After

const getUserCount = new schema.Query(
  new schema.All(User),
  (entries, { isAdmin } = { }) => {
    if (isAdmin !== undefined)
      return entries.filter(user => user.isAdmin === isAdmin).length;
    return entries.length;
  },
);

const userCount = useQuery(getUserCount);
const adminCount = useQuery(getUserCount, { isAdmin: true });

Before

export const PostResource = createResource({
  path: '/posts/:id',
  schema: Post,
}).extend(Base => ({
  vote: new RestEndpoint({
    path: '/posts/:id/vote',
    method: 'POST',
    body: undefined,
    schema: Post,
    getOptimisticResponse(snapshot, { id }) {
      const { data } = snapshot.getResponse(Base.get, { id });
      if (!data) throw new AbortOptimistic();
      return {
        id,
        votes: data.votes + 1,
      };
    },
  }),
}));

After

export const PostResource = createResource({
  path: '/posts/:id',
  schema: Post,
}).extend('vote',
  {
    path: '/posts/:id/vote',
    method: 'POST',
    body: undefined,
    schema: Post,
    getOptimisticResponse(snapshot, { id }) {
      const post = snapshot.get(Post, { id });
      if (!post) throw new AbortOptimistic();
      return {
        id,
        votes: post.votes + 1,
      };
    },
  },
);

TODO

  • Add controller.get and snapshot.get
  • Add useQuery
  • Add Query schema
  • Handle Union inference needing extra arguments (useQuery should not use generics for args, but should accept schema's args, we need to do something about url using these extra args...)
  • Remove queryEndpoint, Index
  • Update docs to use snap.get() in getOptimisticResponse
  • Docs: Schema table, add Query schema, remove Query and Index from endpoints
  • docs: update README references
  • docs: Add blog draft with changes

Followup

  • infer -> buildKey?
  • Infer caching
  • codemod and link in release docs
  • Future release:
    • ctrl.set()

Open Questions

  • Should we get rid of AbortOptimistic and simply abort on any exception?
    • If so we could simply try to access data and if it doesn't exist, it would abort
    • If we lied about the types here to make types work then it wouldn't work well for middlewares that don't want to throw. We could change types just for snapshot but would probably be unexpected
    • Answer: No, the explicit handling makes it more readable; This will definitely silence errors that people can easily fix.

Copy link

changeset-bot bot commented Jan 9, 2024

🦋 Changeset detected

Latest commit: c8944cb

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 16 packages
Name Type
@data-client/normalizr Minor
@data-client/endpoint Minor
@data-client/react Minor
@data-client/core Minor
@data-client/rest Minor
@data-client/graphql Minor
@data-client/redux Minor
@data-client/test Minor
@data-client/hooks Patch
example-benchmark Patch
normalizr-github-example Patch
normalizr-redux-example Patch
normalizr-relationships Patch
@data-client/img Minor
rdc-website Patch
coinbase-lite Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

Copy link

vercel bot commented Jan 18, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
rest-hooks ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jan 18, 2024 11:39am

@ntucker ntucker force-pushed the schema-usecache branch 5 times, most recently from e795722 to 586af8c Compare January 21, 2024 14:06
@ntucker ntucker requested a review from notwillk February 13, 2024 11:47
@ntucker ntucker force-pushed the schema-usecache branch 2 times, most recently from ee279cb to c64546b Compare February 14, 2024 10:24
@ntucker ntucker changed the title feat: Use Querable schemas in useCache() feat: Queries, Queryable, and useQuery Feb 14, 2024
@ntucker ntucker force-pushed the schema-usecache branch 12 times, most recently from d47848d to 48e27c5 Compare February 16, 2024 10:43
@ntucker ntucker force-pushed the master branch 2 times, most recently from f750e4e to 8377e0a Compare February 23, 2024 13:47
@ntucker ntucker force-pushed the schema-usecache branch 3 times, most recently from ed30623 to 5d3a298 Compare February 23, 2024 14:34
Copy link

codecov bot commented Feb 23, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 98.70%. Comparing base (3e0e917) to head (c8944cb).

Additional details and impacted files
@@           Coverage Diff           @@
##           master    #2921   +/-   ##
=======================================
  Coverage   98.70%   98.70%           
=======================================
  Files         117      117           
  Lines        2081     2085    +4     
  Branches      418      417    -1     
=======================================
+ Hits         2054     2058    +4     
  Misses         16       16           
  Partials       11       11           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@ntucker ntucker force-pushed the schema-usecache branch 8 times, most recently from 3b96fe7 to 4608cf5 Compare February 29, 2024 11:23
@ntucker ntucker force-pushed the schema-usecache branch 10 times, most recently from f8d6158 to ad0a5d6 Compare March 5, 2024 10:09
@ntucker ntucker merged commit 6e55026 into master Mar 6, 2024
24 checks passed
@ntucker ntucker deleted the schema-usecache branch March 6, 2024 09:15
@github-actions github-actions bot mentioned this pull request Mar 6, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant