--- url: https://canary.warp-drive.io/guides/installation.md description: >- Install @warp-drive/core and @warp-drive/json-api with exact pinned versions, then add the reactivity package and install import for Ember, React, or TC39 Signals. --- :::warning **🚧 Pardon Our Stardust!** ✨ [PolarisMode](/guides/the-manual/schemas/resources/polaris-mode.md) Resources Aren't quite ready! Ember apps should currently use [LegacyMode](/guides/the-manual/schemas/resources/legacy-mode.md) and additionally install both `@warp-drive/legacy` and `@warp-drive/utilities`. Non-Ember apps should wait for PolarisMode to become recommended in V6, or limit usage to experimental exploration. ::: # Installation ::: tip 💡 ***Warp*Drive** simplifies distribution using npm channel tags * `@lts` | `@latest` | `@beta` | `@canary` ::: To use ***Warp*Drive**, you will install `@warp-drive/core`, a cache\[^1], and a reactivity system such as [emberjs](#ember), [TC39 Signals](#tc39-signals) or even [react](#react). \[^1]: We recommend using `@warp-drive/json-api` as your cache even if your API is not [{json:api}](https://jsonapi.org). :::tabs key:install \== latest ::: code-group ```sh [pnpm] pnpm add -E @warp-drive/core@latest @warp-drive/json-api@latest ``` ```sh [npm] npm add -E @warp-drive/core@latest @warp-drive/json-api@latest ``` ```sh [yarn] yarn add -E @warp-drive/core@latest @warp-drive/json-api@latest ``` ```sh [bun] bun add --exact @warp-drive/core@latest @warp-drive/json-api@latest ``` \== lts ::: code-group ```sh [pnpm] pnpm add -E @warp-drive/core@lts @warp-drive/json-api@lts ``` ```sh [npm] npm add -E @warp-drive/core@lts @warp-drive/json-api@lts ``` ```sh [yarn] yarn add -E @warp-drive/core@lts @warp-drive/json-api@lts ``` ```sh [bun] bun add --exact @warp-drive/core@lts @warp-drive/json-api@lts ``` \== beta ::: code-group ```sh [pnpm] pnpm add -E @warp-drive/core@beta @warp-drive/json-api@beta ``` ```sh [npm] npm add -E @warp-drive/core@beta @warp-drive/json-api@beta ``` ```sh [yarn] yarn add -E @warp-drive/core@beta @warp-drive/json-api@beta ``` ```sh [bun] bun add --exact @warp-drive/core@beta @warp-drive/json-api@beta ``` \== canary ::: code-group ```sh [pnpm] pnpm add -E @warp-drive/core@canary @warp-drive/json-api@canary ``` ```sh [npm] npm add -E @warp-drive/core@canary @warp-drive/json-api@canary ``` ```sh [yarn] yarn add -E @warp-drive/core@canary @warp-drive/json-api@canary ``` ```sh [bun] bun add --exact @warp-drive/core@canary @warp-drive/json-api@canary ``` ::: Complete your installation by installing and configuring the reactive framework of your choosing. ### Available Frameworks * [ember](#ember) * [react](#react) * [svelte](#svelte) (🚧 Coming Soon) * [vue](#vue) (🚧 Coming Soon) * [TC39 Signals](#tc39-signals) Don't see your framework listed yet? Reactive frameworks can typically be implemented in 15-30 lines of JS (before you add docs and types of course ;)). We're happy to add support for any framework that supports fine-grained signals based reactivity. ## Lockstep Versioning :::tip 💡 **TIP** Use Exact Versions in package.json We find its best to use exact versions instead of ranges as all ***Warp*Drive** packages should be upgraded together at once. ::: ***Warp*Drive** packages follow a lockstep versioning approach: all dependencies and peer-dependencies between the project's own packages are version-locked at the time of publish. For instance, `@warp-drive/utilities@5.6.0` has a peer-dependency on `@warp-drive/core@5.6.0`. If any other version were present (even a differing patch version such as `5.6.1`) it would create a conflict. All of the installation commands listed in this guide pin the version for this reason. ## Other Packages ***Warp*Drive** offers additional packages for features that don't quite meet the bar for being included in core, or have been deprecated and removed from the core experience. * `@warp-drive/utilities` provides commonly needed request builder, handler and string utils. * `@warp-drive/experiments` provides bleeding edge unstable features we're prototyping like SharedWorker and PersistedCache * `@warp-drive/legacy` provides extended life-support for features that have been removed from core. :::tabs key:install \== latest ::: code-group ```sh [pnpm] pnpm add -E @warp-drive/utilities@latest pnpm add -E @warp-drive/legacy@latest pnpm add -E @warp-drive/experiments@latest ``` ```sh [npm] npm add -E @warp-drive/utilities@latest npm add -E @warp-drive/legacy@latest npm add -E @warp-drive/experiments@latest ``` ```sh [yarn] yarn add -E @warp-drive/utilities@latest yarn add -E @warp-drive/legacy@latest yarn add -E @warp-drive/experiments@latest ``` ```sh [bun] bun add --exact @warp-drive/utilities@latest bun add --exact @warp-drive/legacy@latest bun add --exact @warp-drive/experiments@latest ``` \== lts ::: code-group ```sh [pnpm] pnpm add -E @warp-drive/utilities@lts pnpm add -E @warp-drive/legacy@lts pnpm add -E @warp-drive/experiments@lts ``` ```sh [npm] npm add -E @warp-drive/utilities@lts npm add -E @warp-drive/legacy@lts npm add -E @warp-drive/experiments@lts ``` ```sh [yarn] yarn add -E @warp-drive/utilities@lts yarn add -E @warp-drive/legacy@lts yarn add -E @warp-drive/experiments@lts ``` ```sh [bun] bun add --exact @warp-drive/utilities@lts bun add --exact @warp-drive/legacy@lts bun add --exact @warp-drive/experiments@lts ``` \== beta ::: code-group ```sh [pnpm] pnpm add -E @warp-drive/utilities@beta pnpm add -E @warp-drive/legacy@beta pnpm add -E @warp-drive/experiments@beta ``` ```sh [npm] npm add -E @warp-drive/utilities@beta npm add -E @warp-drive/legacy@beta npm add -E @warp-drive/experiments@beta ``` ```sh [yarn] yarn add -E @warp-drive/utilities@beta yarn add -E @warp-drive/legacy@beta yarn add -E @warp-drive/experiments@beta ``` ```sh [bun] bun add --exact @warp-drive/utilities@beta bun add --exact @warp-drive/legacy@beta bun add --exact @warp-drive/experiments@beta ``` \== canary ::: code-group ```sh [pnpm] pnpm add -E @warp-drive/utilities@canary pnpm add -E @warp-drive/legacy@canary pnpm add -E @warp-drive/experiments@canary ``` ```sh [npm] npm add -E @warp-drive/utilities@canary npm add -E @warp-drive/legacy@canary npm add -E @warp-drive/experiments@canary ``` ```sh [yarn] yarn add -E @warp-drive/utilities@canary yarn add -E @warp-drive/legacy@canary yarn add -E @warp-drive/experiments@canary ``` ```sh [bun] bun add --exact @warp-drive/utilities@canary bun add --exact @warp-drive/legacy@canary bun add --exact @warp-drive/experiments@canary ``` ::: ## 🐹 Ember.js {#ember} Install `@warp-drive/ember` and (optionally) install support for the EmberInspector data pane by installing `@ember-data/debug`. :::tabs key:install \== latest ::: code-group ```sh [pnpm] pnpm add -E @warp-drive/ember@latest pnpm add -E @ember-data/debug@latest ``` ```sh [npm] npm add -E @warp-drive/ember@latest npm add -E @ember-data/debug@latest ``` ```sh [yarn] yarn add -E @warp-drive/ember@latest yarn add -E @ember-data/debug@latest ``` ```sh [bun] bun add --exact @warp-drive/ember@latest bun add --exact @ember-data/debug@latest ``` \== lts ::: code-group ```sh [pnpm] pnpm add -E @warp-drive/ember@lts pnpm add -E @ember-data/debug@lts ``` ```sh [npm] npm add -E @warp-drive/ember@lts npm add -E @ember-data/debug@lts ``` ```sh [yarn] yarn add -E @warp-drive/ember@lts yarn add -E @ember-data/debug@lts ``` ```sh [bun] bun add --exact @warp-drive/ember@lts bun add --exact @ember-data/debug@lts ``` \== beta ::: code-group ```sh [pnpm] pnpm add -E @warp-drive/ember@beta pnpm add -E @ember-data/debug@beta ``` ```sh [npm] npm add -E @warp-drive/ember@beta npm add -E @ember-data/debug@beta ``` ```sh [yarn] yarn add -E @warp-drive/ember@beta yarn add -E @ember-data/debug@beta ``` ```sh [bun] bun add --exact @warp-drive/ember@beta bun add --exact @ember-data/debug@beta ``` \== canary ::: code-group ```sh [pnpm] pnpm add -E @warp-drive/ember@canary pnpm add -E @ember-data/debug@canary ``` ```sh [npm] npm add -E @warp-drive/ember@canary npm add -E @ember-data/debug@canary ``` ```sh [yarn] yarn add -E @warp-drive/ember@canary yarn add -E @ember-data/debug@canary ``` ```sh [bun] bun add --exact @warp-drive/ember@canary bun add --exact @ember-data/debug@canary ``` ::: Configure your app to use Ember's signals implementation by adding the following import to the top of your application and test setup. ::: code-group ```ts [app/app.ts] import '@warp-drive/ember/install'; ``` ```ts [tests/test-helper.ts] import '@warp-drive/ember/install'; ``` ::: Addons that make use of ***Warp*Drive** should only do the above installation in their tests (including test apps) but not in any published library code. ## React :::tabs key:install \== latest ::: code-group ```sh [pnpm] pnpm add -E @warp-drive/react@latest ``` ```sh [npm] npm add -E @warp-drive/react@latest ``` ```sh [yarn] yarn add -E @warp-drive/react@latest ``` ```sh [bun] bun add --exact @warp-drive/react@latest ``` \== lts ::: code-group ```sh [pnpm] pnpm add -E @warp-drive/react@lts ``` ```sh [npm] npm add -E @warp-drive/react@lts ``` ```sh [yarn] yarn add -E @warp-drive/react@lts ``` ```sh [bun] bun add --exact @warp-drive/react@lts ``` \== beta ::: code-group ```sh [pnpm] pnpm add -E @warp-drive/react@beta ``` ```sh [npm] npm add -E @warp-drive/react@beta ``` ```sh [yarn] yarn add -E @warp-drive/react@beta ``` ```sh [bun] bun add --exact @warp-drive/react@beta ``` \== canary ::: code-group ```sh [pnpm] pnpm add -E @warp-drive/react@canary ``` ```sh [npm] npm add -E @warp-drive/react@canary ``` ```sh [yarn] yarn add -E @warp-drive/react@canary ``` ```sh [bun] bun add --exact @warp-drive/react@canary ``` ::: Even though React does not natively understand signals, ***Warp*Drive** provides a solution that enables React to understand when reactive data used by a component has changed enabling it to properly rerender. We'll cover this more in the [@warp-drive/react documentation](/api/@warp-drive/react/) Configure your app to use our React compatible signals implementation by adding the following import to the top of your application. If you have tests which do not invoke your app, your test setup should also have this import. ::: code-group ```ts [src/app.ts] import '@warp-drive/react/install'; ``` ```ts [src/setupTests.ts] import '@warp-drive/react/install'; ``` ::: Only apps need to do the installation above, libraries providing React components that make use of ***Warp*Drive** should only do the above installation in their tests but not in any published library code. ::: tip React alongside another framework If React components share a page and a store with another framework, such as an Ember app that renders some React components, import `@warp-drive/alien-signals/install` before both frameworks' `install` imports. Memoized values such as [derived fields](/guides/the-manual/schemas/derivations.md) then only recompute when a signal ***Warp*Drive** manages changes, not when state that only a framework tracks, such as an Ember `@tracked` property, changes. See [Using Ember and React on the Same Page](/guides/the-manual/cookbook/multiple-frameworks-on-one-page.md). ::: ## Svelte (🚧 Coming Soon) {#svelte} :::tabs key:install \== latest ::: code-group ```sh [pnpm] pnpm add -E @warp-drive/svelte@latest ``` ```sh [npm] npm add -E @warp-drive/svelte@latest ``` ```sh [yarn] yarn add -E @warp-drive/svelte@latest ``` ```sh [bun] bun add --exact @warp-drive/svelte@latest ``` \== lts ::: code-group ```sh [pnpm] pnpm add -E @warp-drive/svelte@lts ``` ```sh [npm] npm add -E @warp-drive/svelte@lts ``` ```sh [yarn] yarn add -E @warp-drive/svelte@lts ``` ```sh [bun] bun add --exact @warp-drive/svelte@lts ``` \== beta ::: code-group ```sh [pnpm] pnpm add -E @warp-drive/svelte@beta ``` ```sh [npm] npm add -E @warp-drive/svelte@beta ``` ```sh [yarn] yarn add -E @warp-drive/svelte@beta ``` ```sh [bun] bun add --exact @warp-drive/svelte@beta ``` \== canary ::: code-group ```sh [pnpm] pnpm add -E @warp-drive/svelte@canary ``` ```sh [npm] npm add -E @warp-drive/svelte@canary ``` ```sh [yarn] yarn add -E @warp-drive/svelte@canary ``` ```sh [bun] bun add --exact @warp-drive/svelte@canary ``` ::: Configure your app to use Svelte's signals (Runes) for reactivity by adding the following import to the top of your application. If you have tests which do not invoke your app, your test setup should also have this import. ::: code-group ```ts [src/app.ts] import '@warp-drive/svelte/install'; ``` ```ts [src/setupTests.ts] import '@warp-drive/svelte/install'; ``` ::: Only apps need to do the installation above, libraries providing Svelte components that make use of ***Warp*Drive** should only do the above installation in their tests but not in any published library code. ## Vue (🚧 Coming Soon) {#vue} :::tabs key:install \== latest ::: code-group ```sh [pnpm] pnpm add -E @warp-drive/vue@latest ``` ```sh [npm] npm add -E @warp-drive/vue@latest ``` ```sh [yarn] yarn add -E @warp-drive/vue@latest ``` ```sh [bun] bun add --exact @warp-drive/vue@latest ``` \== lts ::: code-group ```sh [pnpm] pnpm add -E @warp-drive/vue@lts ``` ```sh [npm] npm add -E @warp-drive/vue@lts ``` ```sh [yarn] yarn add -E @warp-drive/vue@lts ``` ```sh [bun] bun add --exact @warp-drive/vue@lts ``` \== beta ::: code-group ```sh [pnpm] pnpm add -E @warp-drive/vue@beta ``` ```sh [npm] npm add -E @warp-drive/vue@beta ``` ```sh [yarn] yarn add -E @warp-drive/vue@beta ``` ```sh [bun] bun add --exact @warp-drive/vue@beta ``` \== canary ::: code-group ```sh [pnpm] pnpm add -E @warp-drive/vue@canary ``` ```sh [npm] npm add -E @warp-drive/vue@canary ``` ```sh [yarn] yarn add -E @warp-drive/vue@canary ``` ```sh [bun] bun add --exact @warp-drive/vue@canary ``` ::: Configure your app to use Vue's signals for reactivity by adding the following import to the top of your application. If you have tests which do not invoke your app, your test setup should also have this import. ::: code-group ```ts [src/app.ts] import '@warp-drive/vue/install'; ``` ```ts [src/setupTests.ts] import '@warp-drive/vue/install'; ``` ::: Only apps need to do the installation above, libraries providing Vue components that make use of ***Warp*Drive** should only do the above installation in their tests but not in any published library code. ## TC39-signals {#tc39-signals} :::tabs key:install \== latest ::: code-group ```sh [pnpm] pnpm add -E @warp-drive/tc39-proposal-signals@latest ``` ```sh [npm] npm add -E @warp-drive/tc39-proposal-signals@latest ``` ```sh [yarn] yarn add -E @warp-drive/tc39-proposal-signals@latest ``` ```sh [bun] bun add --exact @warp-drive/tc39-proposal-signals@latest ``` \== lts ::: code-group ```sh [pnpm] pnpm add -E @warp-drive/tc39-proposal-signals@lts ``` ```sh [npm] npm add -E @warp-drive/tc39-proposal-signals@lts ``` ```sh [yarn] yarn add -E @warp-drive/tc39-proposal-signals@lts ``` ```sh [bun] bun add --exact @warp-drive/tc39-proposal-signals@lts ``` \== beta ::: code-group ```sh [pnpm] pnpm add -E @warp-drive/tc39-proposal-signals@beta ``` ```sh [npm] npm add -E @warp-drive/tc39-proposal-signals@beta ``` ```sh [yarn] yarn add -E @warp-drive/tc39-proposal-signals@beta ``` ```sh [bun] bun add --exact @warp-drive/tc39-proposal-signals@beta ``` \== canary ::: code-group ```sh [pnpm] pnpm add -E @warp-drive/tc39-proposal-signals@canary ``` ```sh [npm] npm add -E @warp-drive/tc39-proposal-signals@canary ``` ```sh [yarn] yarn add -E @warp-drive/tc39-proposal-signals@canary ``` ```sh [bun] bun add --exact @warp-drive/tc39-proposal-signals@canary ``` ::: Configure your app to use TC39 Signals for reactivity by adding the following import to the top of your application. If you have tests which do not invoke your app, your test setup should also have this import. ::: code-group ```ts [src/app.ts] import '@warp-drive/tc39-proposal-signals/install'; ``` ```ts [src/setupTests.ts] import '@warp-drive/tc39-proposal-signals/install'; ``` ::: Only apps need to do the installation above, libraries providing code that makes use of ***Warp*Drive** should only do the above installation in their tests but not in any published library code. --- --- url: https://canary.warp-drive.io/guides/installation/unpkg.md description: >- Load prebuilt ESM builds of WarpDrive packages from UNPKG and pick the unpkg, unpkg-dev, unpkg-deprecated, or unpkg-dev-deprecated export condition you need. --- # UNPKG *** Beginning in `5.8`, prebuilt versions of ***Warp*Drive** packages can be used via [UNPKG](https://unpkg.com/). Four builds are provided for each package via the following [export conditions](https://nodejs.org/api/packages.html#conditional-exports). These builds are unminified [JavaScript Modules (ESM)](https://unpkg.com/#nobuild-apps) and retain source code documentation comments. | condition | description | | --------- | ----------- | | ***default*** `unpkg` | production build with all deprecated features removed | | `unpkg-dev` | development build with all deprecated features removed | | `unpkg-deprecated` | production build with all deprecated features available | | `unpkg-dev-deprecated` | development build with all deprecated features available | Example using `@warp-drive/core` | Build | URL | | ----- | --- | | Production | | | Production + Deprecations | | | Development | | | Development + Deprecations | | --- --- url: https://canary.warp-drive.io/guides/configuration.md description: >- Set up WarpDrive's babel build plugin with compatWith and create a store with useRecommendedStore or useLegacyStore, the two steps required before making any request. --- ::: warning 💡 Looking for the [Legacy Package Setup Guide?](./legacy-package-setup/setup/universal) ::: # Setup Before we start working with our data we need to configure ***Warp*Drive**'s [build plugin](#configure-the-build-plugin) and a [Store](#configure-the-store) to manage our data. ## Configure the Build Plugin ***Warp*Drive** uses a [babel plugin](https://www.npmjs.com/package/@embroider/macros) to inject app-specific [configuration](/api/@warp-drive/core/build-config/types/WarpDriveConfig) allowing us to provide advanced dev-mode debugging features, deprecation management, and canary feature toggles. For most projects, the configuration is done inside of the project's babel configuration file. For ember apps that still have an `ember-cli-build` file, this plugin comes built-in to the toolchain and all you need to do is provide it the desired configuration in `ember-cli-build`. ::: tabs key:paradigm \== Simple Config ```ts [babel.config.mjs] import { babelPlugin } from '@warp-drive/core/build-config'; const macros = babelPlugin({ // for universal apps this MUST be at least 5.6 compatWith: '5.6', }); export default { plugins: [ ...macros.js ] } ``` \== Advanced Config ```ts [babel.config.mjs] import { setConfig } from '@warp-drive/core/build-config'; import { buildMacros } from '@embroider/macros/babel'; const Macros = buildMacros({ configure: (config) => { setConfig(config, { // for universal apps this MUST be at least 5.6 compatWith: '5.6' }); }, }); export default { plugins: [ // babel-plugin-debug-macros is temporarily needed // to convert deprecation/warn calls into console.warn [ 'babel-plugin-debug-macros', { flags: [], debugTools: { isDebug: process.env.NODE_ENV !== 'production', source: '@ember/debug', assertPredicateIndex: 1, }, }, 'ember-data-specific-macros-stripping-test', ], ...Macros.babelMacros, ], }; ``` \== Ember Apps ```ts [ember-cli-build.js] 'use strict'; const EmberApp = require('ember-cli/lib/broccoli/ember-app'); const { compatBuild } = require('@embroider/compat'); module.exports = async function (defaults) { const { setConfig } = await import('@warp-drive/core/build-config'); // [!code focus] const { buildOnce } = await import('@embroider/vite'); const app = new EmberApp(defaults, {}); setConfig(app, __dirname, { // [!code focus:9] // this should be the most recent . version for // which all deprecations have been fully resolved // and should be updated when that changes compatWith: '4.12', deprecations: { // ... list individual deprecations that have been resolved here } }); return compatBuild(app, buildOnce); }; ``` ::: ## Configure The Store The [`Store`](/api/@warp-drive/core/classes/Store) is the central piece of the ***Warp*Drive** experience, linking together how we handle requests, the schemas for what our data looks like, how to cache it, and what sort of reactive objects to create for that data. ***Warp*Drive** provides [a utility to quickly setup a store configured with recommended defaults](/api/@warp-drive/core/functions/useRecommendedStore). :::tabs \== 🚧 PolarisMode (preview) > \[!WARNING] > [PolarisMode](/guides/the-manual/schemas/resources/polaris-mode.md) Isn't quite ready! ```ts import { useRecommendedStore } from '@warp-drive/core'; import { JSONAPICache } from '@warp-drive/json-api'; export default useRecommendedStore({ cache: JSONAPICache, schemas: [ // -- your schemas here ], }); ``` \== LegacyMode (recommended, Ember Only) > \[!TIP] > While [LegacyMode](/guides/the-manual/schemas/resources/legacy-mode.md) can work with > Non-Ember apps, we recommend waiting for [PolarisMode](/guides/the-manual/schemas/resources/polaris-mode.md) to become recommended in V6, or limit usage to experimental exploration. ```ts import { useLegacyStore } from '@warp-drive/legacy'; import { JSONAPICache } from '@warp-drive/json-api'; export default useLegacyStore({ linksMode: false, legacyRequests: true, modelFragments: true, cache: JSONAPICache, schemas: [ // -- your schemas here ], }); ``` ::: **That's it!** It's time to start working with your data. Alternatively, to understand more about what the above setup does, you can read about manually configuring the store in the [Advanced Guide](./advanced.md) --- --- url: https://canary.warp-drive.io/guides/configuration/advanced.md description: >- Build a Store class by hand, adding RequestManager, SchemaService, JSONAPICache, instantiateRecord, and DefaultCachePolicy step by step, with Ember Model and migration variants. --- # Advanced Store Configuration ***Warp*Drive** is designed as a series of small packages and primitives with clear interface-driven boundaries between each other and brought together by configuration. The [`Store`](/api/@warp-drive/core/classes/Store) is the central piece of the ***Warp*Drive** experience, linking together how we handle requests, the schemas for what our data looks like, how to cache it, and what sort of reactive objects to create for that data. Here's an example final configuration. Below we'll show each bit in parts and discuss what each does. ::: tip 💡 TIP In frameworks that do DI via contexts, you will want to provide the store via context near the application root. In frameworks like [emberjs](https://emberjs.com) which use a service injection pattern you will want to place the store file in the appropriate location such as `/services/store.ts` In other frameworks you will want to create a singleton store in module state that you will import and use when needed. ::: :::tabs key:config \== Universal ```ts [services/store.ts] import { CacheHandler, Fetch, RequestManager, Store } from '@warp-drive/core'; import { instantiateRecord, registerDerivations, SchemaService, teardownRecord } from '@warp-drive/core/reactive'; import { DefaultCachePolicy } from '@warp-drive/core/store'; import type { CacheCapabilitiesManager, ResourceKey } from '@warp-drive/core/types'; import { JSONAPICache } from '@warp-drive/json-api'; export default class AppStore extends Store { requestManager = new RequestManager() .use([Fetch]) .useCache(CacheHandler); lifetimes = new DefaultCachePolicy({ apiCacheHardExpires: 15 * 60 * 1000, // 15 minutes apiCacheSoftExpires: 1 * 30 * 1000, // 30 seconds constraints: { headers: { 'X-WarpDrive-Expires': true, 'Cache-Control': true, 'Expires': true, } } }); createSchemaService() { const schema = new SchemaService(); registerDerivations(schema); return schema; } createCache(capabilities: CacheCapabilitiesManager) { return new JSONAPICache(capabilities); } instantiateRecord(key: ResourceKey, createArgs?: Record) { return instantiateRecord(this, key, createArgs); } teardownRecord(record: unknown): void { return teardownRecord(record); } } ``` \== Model (Ember Only) ```ts [services/store.ts] import Store, { CacheHandler } from '@ember-data/store'; import type { CacheCapabilitiesManager, ModelSchema, SchemaService } from '@ember-data/store/types'; import RequestManager from '@ember-data/request'; import Fetch from '@ember-data/request/fetch'; import { CachePolicy } from '@ember-data/request-utils'; import JSONAPICache from '@ember-data/json-api'; import type { ResourceKey } from '@warp-drive/core/types'; import type { TypeFromInstance } from '@warp-drive/core/types/record'; import type Model from '@ember-data/model'; import { buildSchema, instantiateRecord, modelFor, teardownRecord } from '@ember-data/model'; export default class AppStore extends Store { requestManager = new RequestManager() .use([Fetch]) .useCache(CacheHandler); lifetimes = new CachePolicy({ apiCacheHardExpires: 15 * 60 * 1000, // 15 minutes apiCacheSoftExpires: 1 * 30 * 1000, // 30 seconds constraints: { headers: { 'X-WarpDrive-Expires': true, 'Cache-Control': true, 'Expires': true, } } }); createSchemaService(): SchemaService { return buildSchema(this); } createCache(capabilities: CacheCapabilitiesManager) { return new JSONAPICache(capabilities); } instantiateRecord(key: ResourceKey, createRecordArgs: Record) { return instantiateRecord.call(this, key, createRecordArgs); } teardownRecord(record: unknown): void { return teardownRecord.call(this, record as Model); } modelFor(type: TypeFromInstance): ModelSchema; modelFor(type: string): ModelSchema; modelFor(type: string): ModelSchema { return (modelFor.call(this, type) as ModelSchema) || super.modelFor(type); } } ``` \== Migration (Ember Only) ```ts [services/store.ts] import Store, { CacheHandler, recordIdentifierFor } from '@ember-data/store'; import type { CacheCapabilitiesManager, ModelSchema } from '@ember-data/store/types'; import RequestManager from '@ember-data/request'; import Fetch from '@ember-data/request/fetch'; import { CachePolicy } from '@ember-data/request-utils'; import JSONAPICache from '@ember-data/json-api'; import type { ResourceKey } from '@warp-drive/core/types'; import type { TypeFromInstance } from '@warp-drive/core/types/record'; import { DelegatingSchemaService } from '@ember-data/model/migration-support'; import type Model from '@ember-data/model'; import { instantiateRecord as instantiateModel, modelFor, teardownRecord as teardownModel } from '@ember-data/model'; import { instantiateRecord, registerDerivations, SchemaService, teardownRecord } from '@warp-drive/core/reactive'; export default class AppStore extends Store { requestManager = new RequestManager() .use([Fetch]) .useCache(CacheHandler); lifetimes = new CachePolicy({ apiCacheHardExpires: 15 * 60 * 1000, // 15 minutes apiCacheSoftExpires: 1 * 30 * 1000, // 30 seconds constraints: { headers: { 'X-WarpDrive-Expires': true, 'Cache-Control': true, 'Expires': true, } } }); createSchemaService() { const schema = new SchemaService(); registerDerivations(schema); return new DelegatingSchemaService(this, schema); } createCache(capabilities: CacheCapabilitiesManager) { return new JSONAPICache(capabilities); } instantiateRecord(key: ResourceKey, createArgs?: Record) { if (this.schema.isDelegated(key)) { return instantiateModel.call(this, key, createRecordArgs) } return instantiateRecord(this, key, createArgs); } teardownRecord(record: unknown): void { const key = recordIdentifierFor(record); if (this.schema.isDelegated(key)) { return teardownModel.call(this, record as Model); } return teardownRecord(record); } modelFor(type: TypeFromInstance): ModelSchema; modelFor(type: string): ModelSchema; modelFor(type: string): ModelSchema { return (modelFor.call(this, type) as ModelSchema) || super.modelFor(type); } } ``` ::: ## Start With A Store The store is the central piece of the ***Warp*Drive** experience. It functions as a coordinator, linking together requests for data with schemas, caching and reactivity. While it's easy to use ***just*** ***Warp*Drive**'s request management, most apps will find they require far more than basic fetch management. For this reason it's often best to start with a Store even when you aren't sure yet. ```ts [services/store.ts] import { Store } from '@warp-drive/core'; export default class AppStore extends Store {} ``` ## Add Basic Request Management [`RequestManager`](/api/@warp-drive/core/classes/RequestManager) provides a chain-of-responsibility style pipeline for helping you handle centralized concerns around requesting and updating data from your backend. ::: tip 💡 Guide → Learn more about [Making Requests](../the-manual/requests/index.md) ::: ```ts [services/store.ts] import { Fetch, RequestManager, Store } from '@warp-drive/core'; // [!code focus] export default class AppStore extends Store { requestManager = new RequestManager() // [!code focus:2] .use([Fetch]); } ``` ## Add a Source for Schema for your Data ***Warp*Drive** uses simple JSON schemas to define the shape and features of reactive objects. Schemas may seem simple, but they come packed with features that will help you build incredible applications. ::: tip 💡 Guide → Learn more about [Resource Schemas](../the-manual/schemas/index.md) ::: :::tabs key:config \== Universal ```ts [services/store.ts] import { Fetch, RequestManager, Store } from '@warp-drive/core'; import { // [!code focus:4] registerDerivations, SchemaService, } from '@warp-drive/core/reactive'; export default class AppStore extends Store { requestManager = new RequestManager() .use([Fetch]); createSchemaService() { // [!code focus:5] const schema = new SchemaService(); registerDerivations(schema); return schema; } } ``` \== Model (Ember Only) ```ts [services/store.ts] import Store from '@ember-data/store'; import type { ModelSchema, SchemaService } from '@ember-data/store/types'; // [!code focus] import RequestManager from '@ember-data/request'; import Fetch from '@ember-data/request/fetch'; import type { TypeFromInstance } from '@warp-drive/core/types/record'; // [!code focus] import { // [!code focus:4] buildSchema, modelFor, } from '@ember-data/model'; export default class AppStore extends Store { requestManager = new RequestManager() .use([Fetch]); createSchemaService(): SchemaService { // [!code focus:3] return buildSchema(this); } modelFor(type: TypeFromInstance): ModelSchema; // [!code focus:6] modelFor(type: string): ModelSchema; modelFor(type: string): ModelSchema { return (modelFor.call(this, type) as ModelSchema) || super.modelFor(type); } } ``` \== Migration (Ember Only) ```ts [services/store.ts] import Store from '@ember-data/store'; import type { ModelSchema } from '@ember-data/store/types'; // [!code focus] import RequestManager from '@ember-data/request'; import Fetch from '@ember-data/request/fetch'; import type { TypeFromInstance } from '@warp-drive/core/types/record'; // [!code focus:2] import { DelegatingSchemaService } from '@ember-data/model/migration-support'; import { // [!code focus:3] modelFor, } from '@ember-data/model'; import { // [!code focus:4] registerDerivations, SchemaService, } from '@warp-drive/core/reactive'; export default class AppStore extends Store { requestManager = new RequestManager() .use([Fetch]); createSchemaService() { // [!code focus:5] const schema = new SchemaService(); registerDerivations(schema); return new DelegatingSchemaService(this, schema); } modelFor(type: TypeFromInstance): ModelSchema; // [!code focus:6] modelFor(type: string): ModelSchema; modelFor(type: string): ModelSchema { return (modelFor.call(this, type) as ModelSchema) || super.modelFor(type); } } ``` ::: ## Add a Cache Do you really need a cache? Are sunsets beautiful? Caching is what powers features like immutability, mutation management, and allows ***Warp*Drive** to understand your relational data. Some caches are simple request/response maps. ***Warp*Drive**'s is not. The Cache deeply understands the structure of your data, ensuring your data remains consistent both within and across requests. Out of the box, ***Warp*Drive** provides a Cache that expects the [{json:api}](https://jsonapi.org) format. This format excels at simiplifying common complex problems around cache consistency and information density. Most APIs can be quickly adapted to work with it, but if a cache built to understand another format would do better it just needs to follow the same interface. ```ts [services/store.ts] import { CacheHandler, Fetch, RequestManager, Store } from '@warp-drive/core'; // [!code focus:1] import { registerDerivations, SchemaService, } from '@warp-drive/core/reactive'; import type { // [!code focus:4] CacheCapabilitiesManager } from '@warp-drive/core/types'; import { JSONAPICache } from '@warp-drive/json-api'; export default class AppStore extends Store { requestManager = new RequestManager() .use([Fetch]) .useCache(CacheHandler); // [!code focus:1] createSchemaService() { const schema = new SchemaService(); registerDerivations(schema); return schema; } createCache(capabilities: CacheCapabilitiesManager) { // [!code focus:3] return new JSONAPICache(capabilities); } } ``` ## Setup Your Data to be Reactive While it is possible to use ***Warp*Drive** to store and retrieve raw json, you'd be missing out on the best part. Reactive objects transform raw cached data into rich, reactive data. The resulting objects are immutable, always displaying the latest state in the cache while preventing accidental or unsafe mutation in your app. :::tabs key:config \== ReactiveResource ```ts [services/store.ts] import { CacheHandler, Fetch, RequestManager, Store } from '@warp-drive/core'; import type { CacheCapabilitiesManager, ResourceKey // [!code focus] } from '@warp-drive/core/types'; import { instantiateRecord, // [!code focus] registerDerivations, SchemaService, teardownRecord // [!code focus] } from '@warp-drive/core/reactive'; import { JSONAPICache } from '@warp-drive/json-api'; export default class AppStore extends Store { requestManager = new RequestManager() .use([Fetch]) .useCache(CacheHandler); createSchemaService() { const schema = new SchemaService(); registerDerivations(schema); return schema; } createCache(capabilities: CacheCapabilitiesManager) { return new JSONAPICache(capabilities); } instantiateRecord(key: ResourceKey, createArgs?: Record) { // [!code focus:3] return instantiateRecord(this, key, createArgs); } teardownRecord(record: unknown): void { // [!code focus:3] return teardownRecord(record); } } ``` \== Model (Ember Only) ```ts [services/store.ts] import Store, { CacheHandler } from '@ember-data/store'; import type { CacheCapabilitiesManager, ModelSchema, SchemaService } from '@ember-data/store/types'; import RequestManager from '@ember-data/request'; import Fetch from '@ember-data/request/fetch'; import JSONAPICache from '@ember-data/json-api'; import type { ResourceKey } from '@warp-drive/core/types'; // [!code focus] import type { TypeFromInstance } from '@warp-drive/core/types/record'; import type Model from '@ember-data/model'; // [!code focus] import { buildSchema, instantiateRecord, // [!code focus] modelFor, teardownRecord // [!code focus] } from '@ember-data/model'; export default class AppStore extends Store { requestManager = new RequestManager() .use([Fetch]) .useCache(CacheHandler); createSchemaService(): SchemaService { return buildSchema(this); } createCache(capabilities: CacheCapabilitiesManager) { return new JSONAPICache(capabilities); } instantiateRecord(key: ResourceKey, createRecordArgs: Record) { // [!code focus:3] return instantiateRecord.call(this, key, createRecordArgs); } teardownRecord(record: unknown): void { // [!code focus:3] return teardownRecord.call(this, record as Model); } modelFor(type: TypeFromInstance): ModelSchema; modelFor(type: string): ModelSchema; modelFor(type: string): ModelSchema { return (modelFor.call(this, type) as ModelSchema) || super.modelFor(type); } } ``` \== Migration (Ember Only) ```ts [services/store.ts] import Store, { CacheHandler, recordIdentifierFor } from '@ember-data/store'; import type { CacheCapabilitiesManager, ModelSchema } from '@ember-data/store/types'; import RequestManager from '@ember-data/request'; import Fetch from '@ember-data/request/fetch'; import JSONAPICache from '@ember-data/json-api'; import type { ResourceKey } from '@warp-drive/core/types'; // [!code focus] import type { TypeFromInstance } from '@warp-drive/core/types/record'; import { DelegatingSchemaService } from '@ember-data/model/migration-support'; import type Model from '@ember-data/model'; // [!code focus] import { instantiateRecord as instantiateModel, // [!code focus] modelFor, teardownRecord as teardownModel // [!code focus] } from '@ember-data/model'; import { instantiateRecord, // [!code focus] registerDerivations, SchemaService, teardownRecord // [!code focus] } from '@warp-drive/core/reactive'; export default class AppStore extends Store { requestManager = new RequestManager() .use([Fetch]) .useCache(CacheHandler); createSchemaService() { const schema = new SchemaService(); registerDerivations(schema); return new DelegatingSchemaService(this, schema); } createCache(capabilities: CacheCapabilitiesManager) { return new JSONAPICache(capabilities); } instantiateRecord(key: ResourceKey, createArgs?: Record) { // [!code focus:6] if (this.schema.isDelegated(key)) { return instantiateModel.call(this, key, createRecordArgs) } return instantiateRecord(this, key, createArgs); } teardownRecord(record: unknown): void { // [!code focus:7] const key = recordIdentifierFor(record); if (this.schema.isDelegated(key)) { return teardownModel.call(this, record as Model); } return teardownRecord(record); } modelFor(type: TypeFromInstance): ModelSchema; modelFor(type: string): ModelSchema; modelFor(type: string): ModelSchema { return (modelFor.call(this, type) as ModelSchema) || super.modelFor(type); } } ``` ::: ## Decide How Long Requests are Valid for with a CachePolicy And of course, what's a great cache without an eviction policy? ***Warp*Drive** provides an interface for creating Cache Policies. Whenever a request is made, the policy is checked to determine if the current cached representation is still valid. Policies also have the ability to subscribe to cache updates and issue invalidation notifications. The `` component subscribes to these notifications and will trigger a reload if necessary if an invalidated request is in active use, letting you craft advanced policies that meet your product's needs. ***Warp*Drive** provides a basic [CachePolicy](/api/@warp-drive/core/types/CachePolicy), [`DefaultCachePolicy`](/api/@warp-drive/core/store/classes/DefaultCachePolicy), with a number of great defaults that is a great starting point for most applications. We configure this basic policy below. The basic policy will invalidate requests based on caching and date headers available on request responses, falling back to a simple time based policy. ```ts [services/store.ts] import { CacheHandler, Fetch, RequestManager, Store } from '@warp-drive/core'; import { instantiateRecord, registerDerivations, SchemaService, teardownRecord } from '@warp-drive/core/reactive'; import { DefaultCachePolicy } from '@warp-drive/core/store'; // [!code focus] import type { CacheCapabilitiesManager, ResourceKey } from '@warp-drive/core/types'; import { JSONAPICache } from '@warp-drive/json-api'; export default class AppStore extends Store { requestManager = new RequestManager() .use([Fetch]) .useCache(CacheHandler); lifetimes = new DefaultCachePolicy({ // [!code focus:9] apiCacheHardExpires: 15 * 60 * 1000, // 15 minutes apiCacheSoftExpires: 1 * 30 * 1000, // 30 seconds constraints: { headers: { 'X-WarpDrive-Expires': true, 'Cache-Control': true, 'Expires': true, } } }); createSchemaService() { const schema = new SchemaService(); registerDerivations(schema); return schema; } createCache(capabilities: CacheCapabilitiesManager) { return new JSONAPICache(capabilities); } instantiateRecord(key: ResourceKey, createArgs?: Record) { return instantiateRecord(this, key, createArgs); } teardownRecord(record: unknown): void { return teardownRecord(record); } } ``` --- --- url: https://canary.warp-drive.io/guides/configuration/react.md description: >- Provide your WarpDrive store to React components with StoreProvider, read it with useStore, and know when a component re-renders. --- # Setup - React This page covers the React-specific setup that comes after [installing `@warp-drive/react`](/guides/installation/#react) and [configuring your store](/guides/configuration/#configure-the-store). ## Provide the Store Once you have a store class, which [Configure The Store](/guides/configuration/#configure-the-store) creates, React components get it through React context. Wrap the app in [``](/api/@warp-drive/react/functions/StoreProvider) and give it that class as its `Store` prop, and it creates the instance for you. To provide a store that already exists, pass the instance as `store` instead; see [Use a Store You Already Have](#use-a-store-you-already-have). ```tsx [src/app.tsx] import { StoreProvider } from '@warp-drive/react'; import AppStore from './store'; import { UserList } from './user-list'; export function App() { return ( ); } ``` The provider keeps the instance it created for as long as it receives the same class, so import the class from a module rather than defining it inside a component, where every render would create a new class and a new, empty store. Even with the same class, React may discard the instance and create another: in development builds, Strict Mode creates the store twice and keeps one. If your app must have exactly one store instance, create it yourself and pass it as `store`. Any component inside the provider reads the store with [`useStore`](/api/@warp-drive/react/functions/useStore). In development builds, calling it outside a `` throws an error. Production builds skip that check, and it returns `null`. ```tsx [src/reload-button.tsx] import { useStore } from '@warp-drive/react'; import { findRecord } from '@warp-drive/utilities/json-api'; export function ReloadButton({ userId }: { userId: string }) { const store = useStore(); return ( ); } ``` The React [``](/api/@warp-drive/react/functions/Request) component reads the store the same way when you don't pass it a `store` prop. Reading the store doesn't re-render a component when its data changes; a [``](/api/@warp-drive/react/functions/ReactiveContext) does that, and `` already wraps its content in one. To render a request's loading, error and content states, see [Reactive Control Flow](/guides/the-manual/reactivity/control-flow.md). ## Use a Store You Already Have Pass an existing instance as the `store` prop when something outside React owns the store: a module that creates it once at startup, a test that sets it up, or a host app that mounts React components into part of its page. Every `` given the same instance provides the same store, so separately mounted React roots share one cache and see the same requests. ```tsx [src/mount-user-list.tsx] import { createRoot } from 'react-dom/client'; import type { Store } from '@warp-drive/core'; import { StoreProvider } from '@warp-drive/react'; import { UserList } from './user-list'; export function mountUserList(element: HTMLElement, store: Store): () => void { const root = createRoot(element); root.render( ); return () => root.unmount(); } ``` The host app calls `mountUserList` with the element to render into and its own store, and calls the returned function when it removes that element. ::: tip Embedding React in an app built with another framework One store can drive components from both frameworks, but each framework only re-renders for its own signals. For components in both to re-render when data changes, import `@warp-drive/alien-signals/install` before either framework's `install` import, so that both frameworks share its signals graph. Memoized values such as [derived fields](/guides/the-manual/schemas/derivations.md) then only recompute when a signal ***Warp*Drive** manages changes, not when state that only a framework tracks, such as an Ember `@tracked` property, changes. See [Can I use multiple frameworks on one page?](/guides/faq/multiple-frameworks.md), and for Ember and React, [Using Ember and React on the Same Page](/guides/the-manual/cookbook/multiple-frameworks-on-one-page.md). An Ember app doesn't need PolarisMode to share its store with React; see [Do I need PolarisMode to share state between Ember and React on the same page?](/guides/faq/polaris-mode-with-ember-and-react.md). ::: --- --- url: https://canary.warp-drive.io/guides/tutorials.md description: >- Learn WarpDrive by building apps step by step, starting with the data layer of a TodoMVC app in Ember, written one request at a time. --- # Tutorials * [TodoMVC](./todomvc/index.md): build the data layer for a TodoMVC app in Ember, one request at a time. --- --- url: https://canary.warp-drive.io/guides/tutorials/todomvc.md description: >- Build the data layer of a TodoMVC app with WarpDrive and Ember. Create the starter with npx @warp-drive/tutorials, run it, and see where you'll write WarpDrive code. --- # TodoMVC :::warning **🚧 Pardon Our Stardust!** The `@warp-drive/tutorials` package isn't published yet, so the `npx` command below doesn't work. Until it is, run the starter from a clone of the WarpDrive repo: ```sh git clone https://github.com/warp-drive-data/warp-drive.git cd warp-drive pnpm install cd packages/tutorials/todomvc-ember/starter pnpm start ``` ::: Let's build the data layer of a TodoMVC app with ***Warp*Drive**. The starter ships the Ember UI and a local API. You write the ***Warp*Drive** part: requests, builders, one handler and a few cache updates. No models, adapters or serializers. Your first request renders todos in chapter 1. From chapter 4 on, each chapter adds one operation: create, edit, toggle, delete, then the bulk controls. Most chapters start with a problem every data layer has, and show how ***Warp*Drive** handles it. ## Chapters | | Chapter | You'll use | | --- | --------------------------------------------------- | ------------------------------------------ | | 1 | [First request](./first-request.md) | `store.request` and `` | | 2 | [Why that worked](./why-that-worked.md) | the four ideas WarpDrive is built on | | 3 | [Request builders](./request-builders.md) | builders and a handler | | 4 | [Create](./create.md) | `createRecord` and invalidation | | 5 | [Edit title](./edit-title.md) | `checkout` and `updateRecord` | | 6 | [Toggle](./toggle.md) | `store.cache.patch` | | 7 | [Delete](./delete.md) | `deleteRecord` | | 8 | [Bulk operations](./bulk-operations.md) | bulk requests, then where to go next | ## Before you start You should know TypeScript and have built something with Ember. You don't need to know ***Warp*Drive**. You need Node.js and [pnpm](https://pnpm.io/). ## Get the starter ```sh npx @warp-drive/tutorials@canary todomvc-ember cd todomvc-ember pnpm install pnpm start ``` Open the URL Vite prints. You should see the TodoMVC header and the filters, with no todos between them. That's right: nothing requests todos until chapter 1. ## What's in the starter ``` todomvc-ember/ api-worker/ the API, in a service worker; you won't touch it app/ components/ the TodoMVC UI, finished data/ builders/ you write these, next to a shipped utils.ts schemas/ the todo schema, finished store.ts the store; you add a handler in chapter 3 routes/ one per filter: index (All), active, completed ``` The UI is done. You add ***Warp*Drive** calls to a few routes and components, and each chapter tells you which. ## The API The app talks to a JSON:API server at `/api`. It runs in the browser as a service worker, so there's nothing to start, and it keeps your changes across reloads. It begins with three todos. To reset it, clear the site data in your browser's developer tools. --- --- url: https://canary.warp-drive.io/guides/tutorials/todomvc/first-request.md description: >- Request the todos with store.request, then render the Future it returns with a block. --- # First request The list is empty because nothing asks the API for todos. Let's fix that. By the end of this chapter three todos are on screen, and every filter works. In ***Warp*Drive** you don't ask for a model. You describe a **request** (a URL and some options) and hand it to the **store**, which every request goes through. The store returns a **Future** right away: a promise that also knows whether it's loading, done or failed. It resolves to a **document**, the whole response, with the records you asked for in its `data`. The store keeps what it receives in its **cache**, and the records are **reactive**: templates showing them update when the cache changes. ## Request the todos The route for the main list, `app/routes/index.ts`, returns an empty model. Have its `model()` hook ask the store for the todos: ```ts model(): { todos?: Future } { return { todos: this.store.request({ url: '/api/todo' }), }; } ``` The route doesn't wait for the response. It hands the `Future` to the page, which decides what to show while it loads. `TodosDocument` is the response's type. The starter defines it in `app/data/schemas/todo.ts` as `ReactiveDataDocument`: a document whose `data` is a list of reactive todos. For now you pass it by hand; in chapter 3 the request carries its own type. The Active and Completed pages have routes of their own. Have each ask for its part of the list: ```ts // app/routes/active.ts todos: this.store.request({ url: '/api/todo?filter[completed]=false' }), // app/routes/completed.ts todos: this.store.request({ url: '/api/todo?filter[completed]=true' }), ``` That's the same request three times, with the URL and the type spelled out in each. Chapter 3 fixes that. ## Render the response The `Future` reaches `app/components/todo-app/todo-provider.gts` as `@todoFuture`, and its template renders nothing yet. Render the `Future` with a `` block: ```handlebars <:loading> <:content as |content|> <:toggle as |list|>{{yield list to="toggle"}} <:list as |list|>{{yield list to="list"}} <:error as |error|>{{this.appState.onUnrecoverableError error}} ``` `` takes the `Future` and renders `<:loading>`, `<:content>` or `<:error>`, depending on where the request is. The todos are `content.data`. The two `@autorefresh` arguments refetch in the background when the store marks the response out of date, which chapter 4 relies on. Without ***Warp*Drive**, every component that fetches tracks its own loading and error state. Here the `Future` carries that state, and `` renders it. ## Check it Reload. Three todos. Click Active, then Completed: each shows its part of the list. The footer's count and "Clear completed" are still empty, and nothing saves yet. Each chapter adds a piece. Next, a short look at why that took so little code. --- --- url: https://canary.warp-drive.io/guides/tutorials/todomvc/why-that-worked.md description: >- The four ideas WarpDrive is built on: requests instead of models, one path for every request, one cached copy of each thing, and read-only records. --- # Why that worked Chapter 1 took a few small edits, and you got loading states, a cache and live records. That isn't magic. It comes from four ideas ***Warp*Drive** is built on, and the rest of the tutorial puts each one to work. Let's find them in the code you just ran. ## 1. You ask with requests, not models Here's the whole of what the route asked for: ```ts this.store.request({ url: '/api/todo' }); ``` There's no model class, adapter or serializer to fit your API into. You send the request your API already understands, and the store handles the response. Because a request is just an object, you can build it in a function and reuse it. ## 2. Every request takes the same path Here's what happened when the route called `store.request`: ``` store.request({ url: '/api/todo' }) │ ▼ CacheHandler ──── fresh response cached for this request? ──► return it │ no ▼ your handlers none yet │ ▼ Fetch ──────────► GET /api/todo ──► API worker │ ▼ JSONAPICache ◄──────────────── JSON:API document │ stores the document, and each todo in it by type and id ▼ the Future resolves: content.data is Todo[] ``` Every request goes through this same pipeline, and your handlers always sit between the cache and the network. So anything you add there, such as headers, auth or logging, every request gets. [Making Requests](../../the-manual/requests/index.md) covers the rest. ## 3. The cache keeps one copy of each thing Look at the cache step in the diagram. The cache doesn't just file away each response. It pulls out each todo and stores it once, by its `type` and `id`. The All, Active and Completed lists don't hold three copies of a todo. They hold the same one. The records are reactive too: when the cache changes a todo, every template showing it updates. So change a todo once, and every list shows the change. ## 4. Schemas describe data, and records are read-only Open `app/data/schemas/todo.ts`: ```ts export const TodoSchema = withDefaults({ type: 'todo', fields: [ { name: 'title', kind: 'field' }, { name: 'completed', kind: 'field' }, ], }); ``` A **resource** is one thing the API returns, such as a single todo, identified by its `type` and `id`. A schema tells the store which fields a resource type has. `type: 'todo'` matches the `type` in the API's responses, and `withDefaults` adds `id`. That's all you write: no model class. Below the schema, the file declares TypeScript interfaces for the same fields, such as `Todo`. The schema is what the store uses at runtime, and the interfaces are what TypeScript checks. ::: tip Try it Delete the `completed` line from `TodoSchema` and reload. The list disappears, and the console says `No field named completed on todo`: a record has exactly the fields its schema declares. Put the line back. ::: The records you get back are read-only. To change a todo, you edit a copy and save it, so a half-finished edit never shows up anywhere else. ## Where they meet `app/data/store.ts` is where you plug in all four: ```ts export default class Store extends useRecommendedStore({ cache: JSONAPICache, schemas: [TodoSchema], handlers: [ // TODO (chapter 3): add the JSON:API handler ], }) {} ``` `useRecommendedStore` gives you a `Store` with sensible defaults. You supply the parts that depend on your API: a cache that understands its response format, the schemas, and the handlers. None of `app/data/` imports Ember. It's plain TypeScript, so the same data layer works in any framework. ## What's next Chapter 3 puts the first two ideas to work. Chapter 1's requests don't send the `Accept` and `Content-Type` headers JSON:API servers expect. And once you can create todos, the store needs to know which requests to refetch, and nothing tells it yet. A builder and a handler fix both. --- --- url: https://canary.warp-drive.io/guides/tutorials/todomvc/request-builders.md description: >- Write each request once, as a builder, and give every request the JSON:API headers with a handler. --- # Request builders Chapter 1 wrote the todo request three times, spelling out the URL and the response type each time, and the footer needs three more. Let's write it once, as a builder. By the end of this chapter the whole footer works. A request is just an object, so a **builder** is a plain function that returns one. It sends nothing. You pass its result to `store.request`, or to ``. ## Write the builders Create a new file, `app/data/builders/query.ts`: ```ts import { withReactiveResponse } from '@warp-drive/core/request'; import type { RequestInfo } from '@warp-drive/core/types/request'; import { buildBaseURL, buildQueryParams } from '@warp-drive/utilities'; import type { Todo, TodosDocument } from '../schemas/todo.ts'; function queryTodos(filter?: { completed: boolean }): RequestInfo { const url = buildBaseURL({ resourcePath: 'todo' }); const query = filter ? `?${buildQueryParams({ 'filter[completed]': filter.completed })}` : ''; return withReactiveResponse({ method: 'GET', url: `${url}${query}`, headers: new Headers({ Accept: 'application/vnd.api+json' }), // 'query' requests for the 'todo' type are invalidated whenever a todo is // created, so every list refetches and picks up the new todo. op: 'query', cacheOptions: { types: ['todo'] }, }); } /** GET /api/todo */ export function getAllTodos(): RequestInfo { return queryTodos(); } /** GET /api/todo?filter[completed]=false */ export function getActiveTodos(): RequestInfo { return queryTodos({ completed: false }); } /** GET /api/todo?filter[completed]=true */ export function getCompletedTodos(): RequestInfo { return queryTodos({ completed: true }); } ``` Each builder returns a `RequestInfo`: a request that will get a `TodosDocument` back. Two helpers from `@warp-drive/utilities` build the URL: `buildBaseURL` makes the `/api/todo` path, and `buildQueryParams` adds the filter. Two lines do more than build a URL: * `withReactiveResponse` records the response type on the request, so callers don't have to. Chapter 1 wrote `store.request` for that. * `op: 'query'` with `cacheOptions: { types: ['todo'] }` registers the request as a list of todos. When a todo is created, the store **invalidates** every such request: it marks the cached response out of date, so `` fetches it again. ## Use them in the routes In `app/routes/index.ts`, replace chapter 1's request with the builder: ```ts // At the top of the file: import { getAllTodos } from '#app/data/builders/query.ts'; // ... todos: this.store.request(getAllTodos()), ``` Do the same in `app/routes/active.ts` and `app/routes/completed.ts`, with `getActiveTodos` and `getCompletedTodos`. ## Use them in the footer Three parts of the footer need todos. Each passes a builder to `` as `@query`, and `` calls `store.request` for you. TodoMVC hides the footer when there are no todos. The footer can't use the page's list to decide: on the Active page that list is filtered, and it can be empty while completed todos still exist. So the footer asks the store for all the todos itself, and shows only if there are any. In `app/components/todo-app/footer.gts`, wrap the `