Skip to content

Commit

Permalink
[DOC serializer] implements MinimumSerializerInterface (#6451) (#6499)
Browse files Browse the repository at this point in the history
  • Loading branch information
runspired committed Sep 25, 2019
1 parent 284c8c3 commit 0ff38fb
Show file tree
Hide file tree
Showing 14 changed files with 380 additions and 43 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import Adapter from '@ember-data/adapter';
import Serializer from '@ember-data/serializer';
import { resolve, all } from 'rsvp';
import { ExistingResourceObject } from '@ember-data/store/-private/ts-interfaces/ember-data-json-api';
import { Dict } from '@ember-data/store/-private/ts-interfaces/utils';
import { ConfidentDict } from '@ember-data/store/-private/ts-interfaces/utils';
import { StableRecordIdentifier } from '@ember-data/store/-private/ts-interfaces/identifier';
import { identifierCacheFor } from '@ember-data/store/-private';
import { set } from '@ember/object';
Expand All @@ -30,8 +30,8 @@ if (IDENTIFIERS) {
let store;
let calls;
let secondaryCache: {
id: Dict<string, string>;
username: Dict<string, string>;
id: ConfidentDict<string>;
username: ConfidentDict<string>;
};
class TestSerializer extends Serializer {
normalizeResponse(_, __, payload) {
Expand Down Expand Up @@ -232,7 +232,7 @@ if (IDENTIFIERS) {
module('Secondary Cache using an attribute as an alternate id', function(hooks) {
let store;
let calls;
let secondaryCache: Dict<string, string>;
let secondaryCache: ConfidentDict<string>;
class TestSerializer extends Serializer {
normalizeResponse(_, __, payload) {
return payload;
Expand Down
1 change: 1 addition & 0 deletions packages/adapter/addon/-private/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ export { determineBodyPromise } from './utils/determine-body-promise';
export { serializeQueryParams } from './utils/serialize-query-params';
export { default as fetch } from './utils/fetch';
export { default as BuildURLMixin } from './build-url-mixin';
export { default as serializeIntoHash } from './utils/serialize-into-hash';
11 changes: 11 additions & 0 deletions packages/adapter/addon/-private/utils/serialize-into-hash.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export default function serializeIntoHash(store, modelClass, snapshot, options = { includeId: true }) {
const serializer = store.serializerFor(modelClass.modelName);

if (typeof serializer.serializeIntoHash === 'function') {
const data = {};
serializer.serializeIntoHash(data, modelClass, snapshot, options);
return data;
}

return serializer.serialize(snapshot, options);
}
7 changes: 2 additions & 5 deletions packages/adapter/addon/json-api.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import { dasherize } from '@ember/string';
import RESTAdapter from './rest';
import { pluralize } from 'ember-inflector';
import { serializeIntoHash } from './-private';

/**
The `JSONAPIAdapter` is the default adapter used by Ember Data. It
Expand Down Expand Up @@ -227,12 +228,8 @@ const JSONAPIAdapter = RESTAdapter.extend({
return pluralize(dasherized);
},

// TODO: Remove this once we have a better way to override HTTP verbs.
updateRecord(store, type, snapshot) {
let data = {};
let serializer = store.serializerFor(type.modelName);

serializer.serializeIntoHash(data, type, snapshot, { includeId: true });
const data = serializeIntoHash(store, type, snapshot);

let url = this.buildURL(type.modelName, snapshot.id, snapshot, 'updateRecord');

Expand Down
14 changes: 5 additions & 9 deletions packages/adapter/addon/rest.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import AdapterError, {
} from '@ember-data/adapter/error';
import { warn } from '@ember/debug';
import { DEBUG } from '@glimmer/env';
import { serializeIntoHash } from './-private';

const Promise = EmberPromise;
const hasJQuery = typeof jQuery !== 'undefined';
Expand Down Expand Up @@ -723,13 +724,11 @@ const RESTAdapter = Adapter.extend(BuildURLMixin, {
@return {Promise} promise
*/
createRecord(store, type, snapshot) {
let data = {};
let serializer = store.serializerFor(type.modelName);
let url = this.buildURL(type.modelName, null, snapshot, 'createRecord');

serializer.serializeIntoHash(data, type, snapshot, { includeId: true });
const data = serializeIntoHash(store, type, snapshot);

return this.ajax(url, 'POST', { data: data });
return this.ajax(url, 'POST', { data });
},

/**
Expand All @@ -749,15 +748,12 @@ const RESTAdapter = Adapter.extend(BuildURLMixin, {
@return {Promise} promise
*/
updateRecord(store, type, snapshot) {
let data = {};
let serializer = store.serializerFor(type.modelName);

serializer.serializeIntoHash(data, type, snapshot);
const data = serializeIntoHash(store, type, snapshot, {});

let id = snapshot.id;
let url = this.buildURL(type.modelName, id, snapshot, 'updateRecord');

return this.ajax(url, 'PUT', { data: data });
return this.ajax(url, 'PUT', { data });
},

/**
Expand Down
6 changes: 3 additions & 3 deletions packages/store/addon/-private/identifiers/cache.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { DEBUG } from '@glimmer/env';
import { warn } from '@ember/debug';
import { Dict } from '../ts-interfaces/utils';
import { ConfidentDict } from '../ts-interfaces/utils';
import { ResourceIdentifierObject, ExistingResourceObject } from '../ts-interfaces/ember-data-json-api';
import {
StableRecordIdentifier,
Expand Down Expand Up @@ -30,8 +30,8 @@ interface KeyOptions {
_allIdentifiers: StableRecordIdentifier[];
}

type IdentifierMap = Dict<string, StableRecordIdentifier>;
type TypeMap = Dict<string, KeyOptions>;
type IdentifierMap = ConfidentDict<StableRecordIdentifier>;
type TypeMap = ConfidentDict<KeyOptions>;
export type MergeMethod = (
targetIdentifier: StableRecordIdentifier,
matchedIdentifier: StableRecordIdentifier,
Expand Down
10 changes: 8 additions & 2 deletions packages/store/addon/-private/system/fetch-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import { serializerForAdapter } from './store/serializers';
import { InvalidError } from '@ember-data/adapter/error';
import coerceId from './coerce-id';
import { A } from '@ember/array';

import { _findHasMany, _findBelongsTo, _findAll, _query, _queryRecord } from './store/finders';
import RequestCache from './request-cache';
import { CollectionResourceDocument, SingleResourceDocument } from '../ts-interfaces/ember-data-json-api';
Expand Down Expand Up @@ -135,7 +134,14 @@ export default class FetchManager {
},
function(error) {
if (error instanceof InvalidError) {
let parsedErrors = serializer.extractErrors(store, modelClass, error, snapshot.id);
let parsedErrors = error.errors;

if (typeof serializer.extractErrors === 'function') {
parsedErrors = serializer.extractErrors(store, modelClass, error, snapshot.id);
} else {
parsedErrors = errorsArrayToHash(error.errors);
}

throw { error, parsedErrors };
} else {
throw { error };
Expand Down
4 changes: 2 additions & 2 deletions packages/store/addon/-private/system/identity-map.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import InternalModelMap from './internal-model-map';
import { Dict } from '../ts-interfaces/utils';
import { ConfidentDict } from '../ts-interfaces/utils';

/**
@module @ember-data/store
Expand All @@ -13,7 +13,7 @@ import { Dict } from '../ts-interfaces/utils';
@private
*/
export default class IdentityMap {
private _map: Dict<string, InternalModelMap> = Object.create(null);
private _map: ConfidentDict<InternalModelMap> = Object.create(null);

/**
Retrieves the `InternalModelMap` for a given modelName,
Expand Down
8 changes: 4 additions & 4 deletions packages/store/addon/-private/system/internal-model-map.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { assert } from '@ember/debug';
import InternalModel from './model/internal-model';
import { Dict } from '../ts-interfaces/utils';
import { ConfidentDict } from '../ts-interfaces/utils';

/**
@module @ember-data/store
Expand All @@ -17,9 +17,9 @@ import { Dict } from '../ts-interfaces/utils';
@private
*/
export default class InternalModelMap {
private _idToModel: Dict<string, InternalModel> = Object.create(null);
private _idToModel: ConfidentDict<InternalModel> = Object.create(null);
private _models: InternalModel[] = [];
private _metadata: Dict<string, any> | null = null;
private _metadata: ConfidentDict<any> | null = null;

constructor(public modelName: string) {}

Expand Down Expand Up @@ -104,7 +104,7 @@ export default class InternalModelMap {
* @property metadata
* @type Object
*/
get metadata(): Dict<string, any> {
get metadata(): ConfidentDict<any> {
return this._metadata || (this._metadata = Object.create(null));
}

Expand Down
10 changes: 5 additions & 5 deletions packages/store/addon/-private/system/model/internal-model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import { default as recordDataFor, relationshipStateFor } from '../record-data-f
import RecordData from '../../ts-interfaces/record-data';
import { JsonApiResource, JsonApiValidationError } from '../../ts-interfaces/record-data-json-api';
import { Record } from '../../ts-interfaces/record';
import { Dict } from '../../ts-interfaces/utils';
import { ConfidentDict } from '../../ts-interfaces/utils';
import { IDENTIFIERS, RECORD_DATA_ERRORS, RECORD_DATA_STATE, REQUEST_SERVICE } from '@ember-data/canary-features';
import { identifierCacheFor } from '../../identifiers/cache';
import { StableRecordIdentifier } from '../../ts-interfaces/identifier';
Expand Down Expand Up @@ -107,14 +107,14 @@ export default class InternalModel {
__recordArrays: any;
_references: any;
_recordReference: any;
_manyArrayCache: Dict<string, ManyArray> = Object.create(null);
_manyArrayCache: ConfidentDict<ManyArray> = Object.create(null);

// The previous ManyArrays for this relationship which will be destroyed when
// we create a new ManyArray, but in the interim the retained version will be
// updated if inverse internal models are unloaded.
_retainedManyArrayCache: Dict<string, ManyArray> = Object.create(null);
_relationshipPromisesCache: Dict<string, RSVP.Promise<any>> = Object.create(null);
_relationshipProxyCache: Dict<string, PromiseManyArray | PromiseBelongsTo> = Object.create(null);
_retainedManyArrayCache: ConfidentDict<ManyArray> = Object.create(null);
_relationshipPromisesCache: ConfidentDict<RSVP.Promise<any>> = Object.create(null);
_relationshipProxyCache: ConfidentDict<PromiseManyArray | PromiseBelongsTo> = Object.create(null);
currentState: any;
error: any;

Expand Down
10 changes: 8 additions & 2 deletions packages/store/addon/-private/system/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,6 @@ import hasValidId from '../utils/has-valid-id';
import { RequestPromise } from './request-cache';
import { PromiseProxy } from '../ts-interfaces/promise-proxies';
import { DSModel } from '../ts-interfaces/ds-model';

const emberRun = emberRunLoop.backburner;

const { ENV } = Ember;
Expand Down Expand Up @@ -3298,7 +3297,14 @@ function _commit(adapter, store, operation, snapshot) {
},
function(error) {
if (error instanceof InvalidError) {
let parsedErrors = serializer.extractErrors(store, modelClass, error, snapshot.id);
let parsedErrors;

if (typeof serializer.extractErrors === 'function') {
parsedErrors = serializer.extractErrors(store, modelClass, error, snapshot.id);
} else {
parsedErrors = errorsArrayToHash(error.errors);
}

store.recordWasInvalid(internalModel, parsedErrors, error);
} else {
store.recordWasError(internalModel, error);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { Dict } from './utils';
@module @ember-data/store
*/

export type Meta = Dict<string, JSONValue>;
export type Meta = Dict<JSONValue>;

/**
* Serves as a reference to a `Resource` but does not contain
Expand Down Expand Up @@ -74,15 +74,15 @@ export type ResourceIdentifierObject = ExistingResourceIdentifierObject | NewRes
* Contains the data for an existing resource in JSON:API format
*/
export interface ExistingResourceObject extends ExistingResourceIdentifierObject {
meta?: Dict<string, JSONValue>;
attributes?: Dict<string, JSONValue>;
meta?: Dict<JSONValue>;
attributes?: Dict<JSONValue>;
// these are lossy, need improved typing
relationships?: Dict<string, JSONValue>;
links?: Dict<string, JSONValue>;
relationships?: Dict<JSONValue>;
links?: Dict<JSONValue>;
}

interface Document {
meta?: Dict<string, JSONValue>;
meta?: Dict<JSONValue>;
included?: ExistingResourceObject[];
}

Expand Down
Loading

0 comments on commit 0ff38fb

Please sign in to comment.