-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: SchemaRecord, never write a Model again
- Loading branch information
Showing
15 changed files
with
594 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
# compiled output | ||
/dist/ | ||
/dist/**/* | ||
/tmp/ | ||
/types/ | ||
**/*.d.ts | ||
|
||
# dependencies | ||
/bower_components/ | ||
|
||
# misc | ||
/.bowerrc | ||
/.editorconfig | ||
/.ember-cli | ||
/.env* | ||
/.eslintignore | ||
/.eslintrc.js | ||
/.gitignore | ||
/.template-lintrc.js | ||
/.travis.yml | ||
/.watchmanconfig | ||
/bower.json | ||
/config/ember-try.js | ||
/CONTRIBUTING.md | ||
/ember-cli-build.js | ||
/testem.js | ||
/tests/ | ||
/yarn.lock | ||
.gitkeep | ||
|
||
# ember-try | ||
/.node_modules.ember-try/ | ||
/bower.json.ember-try | ||
/package.json.ember-try | ||
|
||
# ember-data | ||
/node-tests | ||
|
||
# whitelist yuidoc's data.json for api docs generation | ||
!/dist/docs/data.json |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
The MIT License (MIT) | ||
|
||
Copyright (C) 2017-2023 Ember.js contributors | ||
Portions Copyright (C) 2011-2017 Tilde, Inc. and contributors. | ||
Portions Copyright (C) 2011 LivingSocial Inc. | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,191 @@ | ||
<p align="center"> | ||
<img | ||
class="project-logo" | ||
src="./ember-data-logo-dark.svg#gh-dark-mode-only" | ||
alt="EmberData SchemaRecord" | ||
width="240px" | ||
title="EmberData SchemaRecord" | ||
/> | ||
<img | ||
class="project-logo" | ||
src="./ember-data-logo-light.svg#gh-light-mode-only" | ||
alt="EmberData SchemaRecord" | ||
width="240px" | ||
title="EmberData SchemaRecord" | ||
/> | ||
</p> | ||
|
||
<p align="center">🌲 Get back to Nature 🐿️ Or shipping 💚</p> | ||
|
||
SchemaRecord is: | ||
- ⚡️ Fast | ||
- 📦 Tiny | ||
- ✨ Optimized | ||
- 🚀 Scalable | ||
- :electron: Universal | ||
|
||
Never write a Model again. | ||
|
||
This package provides presentation capabilities for your resource data. It works together with an [*Ember***Data**](https://github.com/emberjs/data/) [Cache](https://github.com/emberjs/data/blob/main/ember-data-types/cache/cache.ts) and associated Schemas to simplify the most complex parts of your state management. | ||
|
||
## Installation | ||
|
||
Install using your javascript package manager of choice. For instance with [pnpm](https://pnpm.io/) | ||
|
||
```no-highlight | ||
pnpm add @ember-data/schema-record | ||
``` | ||
|
||
## Getting Started | ||
|
||
If this package is how you are first learning about EmberData, we recommend starting with learning about the [Store](https://github.com/emberjs/data/blob/main/packages/store/README.md) and [Requests](https://github.com/emberjs/data/blob/main/packages/request/README.md) | ||
|
||
## 🚀 Setup | ||
|
||
SchemaRecord integrates with EmberData via the Store's resource lifecycle hooks. | ||
When EmberData needs to create a new presentation class to pair with some resource | ||
data, it calls `instantiateRecord`. When it no longer needs that class, it will call | ||
`teardownRecord`. | ||
|
||
```ts | ||
import Store from '@ember-data/store'; | ||
import SchemaRecord from '@ember-data/schema-record'; | ||
import Cache from '@ember-data/json-api'; | ||
|
||
const DestroyHook = Symbol.for('destroy'); | ||
|
||
export default class extends Store { | ||
instantiateRecord(identifier) { | ||
return new SchemaRecord(this, identifier); | ||
} | ||
|
||
teardownRecord(record: SchemaRecord): void { | ||
record[DestroyHook](); | ||
} | ||
} | ||
``` | ||
|
||
## Start Using | ||
|
||
Any Store method that returns records will use SchemaRecord once configured as above. | ||
After that, its up to you what SchemaRecord can do. | ||
|
||
SchemaRecord's behavior is driven by the Schemas you register with the Store's Schema | ||
Service. Schemas are simple json objects that follow a pattern. | ||
|
||
You could manually construct schemas, though that would be laborious. We recommend | ||
compiling schemas from another available source such as your API's types. If you don't | ||
have a source from which to compile schemas, consider using `@ember-data/schema-dsl`. | ||
|
||
The Schema DSL allows authoring rich, expressive schemas using familiar Typescript and | ||
Decorators, which compile at build into json schemas you can deliver to your app either | ||
in your asset bundle, via a separate fetch, or from your API. | ||
|
||
The Schema DSL will also compile and register types for your schemas that give you robust | ||
typescript support. | ||
|
||
## Main Paradigms | ||
|
||
### Immutability | ||
|
||
SchemaRecord is Immutable. This means by design you cannot mutate a SchemaRecord instance. | ||
|
||
How then do you make edits and preserve changes? | ||
|
||
### Mutation Workflows | ||
|
||
Edits are performed in mutation workflows. A workflow is begun by forking the store. | ||
Forks are cheap copy-on-write scopes that allow you to make changes in isolation without | ||
affecting the global state of the application (until you want to). You can even fork forks, though its probably not that useful to do so in the common case. | ||
|
||
```ts | ||
const fork = await store.fork(); | ||
``` | ||
|
||
Forks are not themselves editable, they are just a pre-requisite. | ||
There are three ways to get an editable SchemaRecord instance. | ||
|
||
1. Create a new record with `const editable = fork.createRecord(<type>, data)` | ||
2. Checkout an existing record in edit mode: `const editable = fork.checkoutRecord(record)` | ||
3. Access a related record on a record already in edit mode: `const editableFriend = editable.bestFriend` | ||
|
||
If you decide you want to discard your changes, there's no need to rollback. Simply | ||
dereferencing the fork and any records you've received from it will cause it to GC. | ||
|
||
However, explicitly calling `fork.deref()` will ensure that if you did forget to dereference | ||
any records and left them around somewhere as a variable, they'll blow up with a useful | ||
error if used again. | ||
|
||
To save changes, call `fork.request(saveRecord(editable))`. Saving changes will only commit | ||
the changes to the fork, it won't commit them upstream. To reflect the changes upstream, call | ||
`await fork.merge(store)`. In most cases, `store` should be the store you forked from, though | ||
it is allowed to attempt to merge into a parent `store` as well. | ||
|
||
```ts | ||
// get a fork for editing | ||
const fork = await store.fork(); | ||
|
||
// create a new record | ||
const user = fork.createRecord('user', { name: 'Chris' }); | ||
|
||
// save the record | ||
await fork.request(createRecord(user)); | ||
|
||
// reflect the changes back to the original store | ||
await store.merge(fork); | ||
``` | ||
|
||
> Note: merging behavior is determined by the Cache implementation. The implementations | ||
> maintained by the EmberData team will merge both persisted and unpersisted changes back | ||
> to the upstream (preserving them as remote and local state respectively). This approach | ||
> allows developers to choose to optimistically vs pessimistically update the global state. | ||
### Optimistic UX | ||
|
||
```ts | ||
// get a fork for editing | ||
const fork = await store.fork(); | ||
|
||
// create a new record | ||
const user = fork.createRecord('user', { name: 'Chris' }); | ||
|
||
// reflect the (dirty) changes back to the original store | ||
await store.merge(fork); | ||
|
||
// save the record | ||
await fork.request(createRecord(user)); | ||
|
||
// reflect the (clean) changes back to the original store | ||
await store.merge(fork); | ||
``` | ||
|
||
## Schema Format | ||
|
||
The schema format is the array representation of a Map structure. From which | ||
we will populate or append to a Map! | ||
|
||
```ts | ||
[ | ||
[ 'user', <user-schema> ], | ||
[ 'company', <company-schema> ], | ||
] | ||
``` | ||
|
||
It follows this signature: | ||
|
||
```ts | ||
type ResourceType = string; // 'user' | ||
type FieldName = string; // 'name' | ||
type FieldDef = { | ||
name: string; | ||
type: string | null; | ||
kind: 'resource' | 'collection' | 'attribute' | 'derivation' | 'object' | 'array'; | ||
options: Record<string, unknown>; | ||
}; | ||
|
||
type ResourceSchema = Array<[FieldName, FieldDef]> | ||
type Schemas = Array<[ResourceType, ResourceSchema]> | ||
``` | ||
You'll find this syntax is capable of describing most conceivable behaviors, including | ||
some emergent ones we're sure we haven't thought of yet. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,93 @@ | ||
const requireModule = require('@ember-data/private-build-infra/src/utilities/require-module'); | ||
const getEnv = require('@ember-data/private-build-infra/src/utilities/get-env'); | ||
const detectModule = require('@ember-data/private-build-infra/src/utilities/detect-module'); | ||
|
||
const pkg = require('./package.json'); | ||
|
||
module.exports = { | ||
name: pkg.name, | ||
|
||
options: { | ||
'@embroider/macros': { | ||
setOwnConfig: {}, | ||
}, | ||
}, | ||
|
||
_emberDataConfig: null, | ||
configureEmberData() { | ||
if (this._emberDataConfig) { | ||
return this._emberDataConfig; | ||
} | ||
const app = this._findHost(); | ||
const isProd = /production/.test(process.env.EMBER_ENV); | ||
const hostOptions = app.options?.emberData || {}; | ||
const debugOptions = Object.assign( | ||
{ | ||
LOG_PAYLOADS: false, | ||
LOG_OPERATIONS: false, | ||
LOG_MUTATIONS: false, | ||
LOG_NOTIFICATIONS: false, | ||
LOG_REQUESTS: false, | ||
LOG_REQUEST_STATUS: false, | ||
LOG_IDENTIFIERS: false, | ||
LOG_GRAPH: false, | ||
LOG_INSTANCE_CACHE: false, | ||
}, | ||
hostOptions.debug || {} | ||
); | ||
|
||
const HAS_DEBUG_PACKAGE = detectModule(require, '@ember-data/debug', __dirname, pkg); | ||
const HAS_META_PACKAGE = detectModule(require, 'ember-data', __dirname, pkg); | ||
|
||
const includeDataAdapterInProduction = | ||
typeof hostOptions.includeDataAdapterInProduction === 'boolean' | ||
? hostOptions.includeDataAdapterInProduction | ||
: HAS_META_PACKAGE; | ||
|
||
const includeDataAdapter = HAS_DEBUG_PACKAGE ? (isProd ? includeDataAdapterInProduction : true) : false; | ||
const DEPRECATIONS = require('@ember-data/private-build-infra/src/deprecations')(hostOptions.compatWith || null); | ||
const FEATURES = require('@ember-data/private-build-infra/src/features')(isProd); | ||
|
||
const ALL_PACKAGES = requireModule('@ember-data/private-build-infra/virtual-packages/packages.js'); | ||
const MACRO_PACKAGE_FLAGS = Object.assign({}, ALL_PACKAGES.default); | ||
delete MACRO_PACKAGE_FLAGS['HAS_DEBUG_PACKAGE']; | ||
|
||
Object.keys(MACRO_PACKAGE_FLAGS).forEach((key) => { | ||
MACRO_PACKAGE_FLAGS[key] = detectModule(require, MACRO_PACKAGE_FLAGS[key], __dirname, pkg); | ||
}); | ||
|
||
// copy configs forward | ||
const ownConfig = this.options['@embroider/macros'].setOwnConfig; | ||
ownConfig.compatWith = hostOptions.compatWith || null; | ||
ownConfig.debug = debugOptions; | ||
ownConfig.deprecations = Object.assign(DEPRECATIONS, ownConfig.deprecations || {}, hostOptions.deprecations || {}); | ||
ownConfig.features = Object.assign({}, FEATURES); | ||
ownConfig.includeDataAdapter = includeDataAdapter; | ||
ownConfig.packages = MACRO_PACKAGE_FLAGS; | ||
ownConfig.env = getEnv(ownConfig); | ||
|
||
this._emberDataConfig = ownConfig; | ||
return ownConfig; | ||
}, | ||
|
||
included() { | ||
this.configureEmberData(); | ||
return this._super.included.call(this, ...arguments); | ||
}, | ||
|
||
treeForVendor() { | ||
return; | ||
}, | ||
treeForPublic() { | ||
return; | ||
}, | ||
treeForStyles() { | ||
return; | ||
}, | ||
treeForAddonStyles() { | ||
return; | ||
}, | ||
treeForApp() { | ||
return; | ||
}, | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
const macros = require('@ember-data/private-build-infra/src/v2-babel-build-pack'); | ||
|
||
module.exports = { | ||
plugins: [ | ||
...macros, | ||
// '@embroider/macros/src/babel/macros-babel-plugin.js', | ||
['@babel/plugin-transform-runtime', { loose: true }], | ||
['@babel/plugin-transform-typescript', { allowDeclareFields: true }], | ||
['@babel/plugin-proposal-decorators', { legacy: true, loose: true }], | ||
['@babel/plugin-transform-private-methods', { loose: true }], | ||
['@babel/plugin-transform-class-properties', { loose: true }], | ||
], | ||
}; |
Oops, something went wrong.