Ember.js Berlin - July 13th, 2021
@_fnovy
hello@fnovy.com
mydea
# app/gql/queries/user-by-email.graphql
query userByEmail($email: String!) {
userByEmail(email: $email) {
id
email
name
roles {
id
name
}
}
}
import { queryManager } from 'ember-apollo-client';
import query from 'my-app/gql/queries/user-by-email.graphql';
export default class MyService extends Service {
@queryManager apollo;
getUserForEmail(email) {
let variables = { email: 'francesco@fabscale.com' };
return this.apollo.query({ query, variables }, 'userByEmail');
}
}
{
id: '1',
email: 'francesco@fabscale.com',
name: 'Francesco Novy',
roles: [
{
id: '1',
name: 'Admin',
},
{
id: '6',
name: 'Maintenance manager',
},
],
}
Apollo allows to cache full requests
The idea is good, but...
import query from 'my-app/gql/queries/user-by-email.graphql';
// Will hit the network
let user = await this.apollo.query({
query,
variables: { email: 'francesco@fabscale.com'}
}, 'userByEmail');
// Will not hit the network, but re-use the previous response
let user2 = await this.apollo.query({
query,
variables: { email: 'francesco@fabscale.com'}
}, 'userByEmail');
// Will hit the network, as variables are different
let user = await this.apollo.query({
query,
variables: { email: 'anne@fabscale.com'}
}, 'userByEmail');
import query from 'my-app/gql/queries/user-by-email.graphql';
import mutation from 'my-app/gql/mutations/update-user.graphql';
let user = await this.apollo.query({
query,
variables: { email: 'francesco@fabscale.com'}
}, 'userByEmail');
await this.apollo.mutate({
mutation,
variables: { email: 'francesco@fabscale.com', name: 'Francesco Smith' }
}, 'updateUser');
// Will not hit the network, but re-use the previous response
let user2 = await this.apollo.query({
query,
variables: { email: 'francesco@fabscale.com'}
}, 'userByEmail');
// user2.name --> still "Francesco Novy"
import usersQuery from 'fabscale-app/gql/queries/users.graphql';
import userByEmailQuery from 'fabscale-app/gql/queries/user-by-email.graphql';
export default class UserStore extends Service {
@service storeManager;
loadUsers() {
return this.storeManager.query({
query: usersQuery,
variables: {}
}, {
namespace: 'users',
cacheEntity: 'User',
cacheSeconds: 300
});
}
loadUser(email) {
return this.storeManager.query({
query: userByEmailQuery,
variables: { email }
}, {
namespace: 'userByEmail',
cacheEntity: 'User'
cacheId: email,
cacheSeconds: 500
});
}
}
import editUserMutation from 'fabscale-app/gql/mutations/edit-user.graphql';
export default class UserStore extends Service {
// ...
async editUser(email, name) {
return await this.storeManager.mutate({
mutation: editUserMutation,
variables: { email, name }
}, {
namespace: 'editUser',
invalidateCache: [
{
cacheEntity: 'User',
},
{
cacheEntity: 'User',
cacheId: email,
},
],
});
}
}
export default class StoreManagerService extends Service {
@queryManager apollo;
query(
options,
{
namespace,
cacheEntity,
cacheId,
cacheSeconds = 60,
} = {}
) {
let useCache = this._checkShouldUseCache(options, {
cacheEntity,
cacheId,
cacheSeconds,
});
// Generally, use `cache-first` as strategy, to avoid repeated lookups
// However, if the last query was longer ago than the specified `cacheSeconds`,
// use `network-only` to force re-fetching it
let fetchPolicy = useCache ? 'cache-first' : 'network-only';
return this.apollo.query(
Object.assign({ fetchPolicy }, options),
namespace
);
}
}
export default class StoreManagerService extends Service {
_checkShouldUseCache({ cacheEntity, cacheId, cacheSeconds }) {
let { storeCache } = this;
let cache = storeCache.getCache(cacheEntity);
let lastLookup = cacheId ? cache.getForId(cacheId) : cache.getOverall();
let now = +new Date() / 1000;
// If the last actual query was longer ago than the specified `cacheSeconds`
// If `cacheSeconds` is 0, we always want to re-fetch
// If no lookup was made yet, we always want to re-fetch
let lastLookupIsOld =
!cacheSeconds || !lastLookup || lastLookup < now - cacheSeconds;
// We only update the last lookup time if we are re-fetching
// To avoid the next lookup being pushed out indefinitely
if (lastLookupIsOld) {
if (cacheId) {
cache.setForId(cacheId, now);
} else {
cache.setOverall(now);
}
}
return !lastLookupIsOld;
}
import { Resource } from 'ember-could-get-used-to-this';
// app/helpers/resources/load-user.js
export default class LoadUserResource extends Resource {
@service userStore;
@tracked isError = false;
@tracked error;
@tracked data;
get value() {
let isLoading = this.loadDataTask.isRunning;
let { isError } = this;
let data = isError ? this.error : this.data;
return {
isLoading,
data,
isError,
};
}
// ...
}
export default class LoadUserResource extends Resource {
// ...
setup() {
let [email] = this.args.positional;
this.loadDataTask.perform(options);
}
teardown() {
this.loadDataTask.cancelAll();
}
@restartableTask
*loadDataTask(email) {
this.isError = false;
try {
this.data = yield this.userStore.loadUser(email);
} catch (error) {
this.error = error.message;
this.isError = true;
}
}
}
{{#let
(resources/load-user 'francesco@fabscale.com')
as |resource|
}}
{{#if resource.isLoading}}
Loading...
{{else if resource.isError}}
Error: {{resource.data}}
{{else}}
Your name: {{resource.data.name}}
{{/if}}
{{/let}}
@_fnovy
hello@fnovy.com
mydea