Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Some quarantine refactor #441

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 8 additions & 6 deletions addon/utils/build-url.ts
Expand Up @@ -20,7 +20,7 @@ export function _getModelName(clazz: typeof Model): string {
// prettier-ignore
clazz.modelName // modern use
// @ts-ignore
|| clazz.typeKey // legacy fallback
|| clazz.typeKey // legacy fallback
);
}

Expand Down Expand Up @@ -62,11 +62,13 @@ export function buildOperationUrl<M extends Model>(
return baseUrl;
}

if (baseUrl.charAt(baseUrl.length - 1) === '/') {
return `${baseUrl}${path}`;
} else {
return `${baseUrl}/${path}`;
}
const separator = isFinishedWithSlash(baseUrl) ? '' : '/';

return `${baseUrl}${separator}${path}`;
}

export default buildOperationUrl;

const isFinishedWithSlash = (baseUrl: string) => {
return baseUrl.charAt(baseUrl.length - 1) === '/';
}
51 changes: 33 additions & 18 deletions addon/utils/collection-action.ts
Expand Up @@ -2,36 +2,51 @@ import { assign } from '@ember/polyfills';
import Model from 'ember-data/model';
import { Value as JSONValue } from 'json-typescript';
import { _getModelClass, _getModelName, _getStoreFromRecord, buildOperationUrl } from './build-url';
import { EmberDataRequestType, Hook, HTTPVerb, strictifyHttpVerb } from './types';
import { EmberDataRequestType, Hook, HTTPVerb, responseCallback, strictifyHttpVerb } from './types';

export interface CollectionOperationOptions<IN, OUT> {
type?: HTTPVerb;
path: string;
urlType?: EmberDataRequestType;
ajaxOptions?: any;
before?: Hook<IN, any>;
after?: Hook<any, OUT>;
before?: responseCallback;
after?: responseCallback;
}

export default function collectionOp<IN = any, OUT = any>(options: CollectionOperationOptions<IN, OUT>) {
return function runCollectionOp(this: Model, payload: IN): Promise<OUT> {
const model: Model = this;
const recordClass = _getModelClass(model);
const {
ajaxOptions,
path,
before,
after,
type = 'put',
urlType = 'updateRecord'
} = options;

const recordClass = _getModelClass(this);
const modelName = _getModelName(recordClass);
const store = _getStoreFromRecord(model);
const requestType: HTTPVerb = strictifyHttpVerb(options.type || 'put');
const urlType: EmberDataRequestType = options.urlType || 'updateRecord';
const store = _getStoreFromRecord(this);
const requestType: HTTPVerb = strictifyHttpVerb(type);
const adapter = store.adapterFor(modelName);
const fullUrl = buildOperationUrl(model, options.path, urlType, false);
const data = (options.before && options.before.call(model, payload)) || payload;
return adapter
.ajax(fullUrl, requestType, assign(options.ajaxOptions || {}, { data }))
.then((response: JSONValue) => {
if (options.after && !model.isDestroyed) {
return options.after.call(model, response);
}
const fullUrl = buildOperationUrl(this, path, urlType, false);
const requestOptions = combineOptions(this, payload, before, ajaxOptions);

return response;
});
return adapter
.ajax(fullUrl, requestType, requestOptions)
.then((response: JSONValue) => handleResponse(this, response, after))
};
}

const combineOptions = (model: Model, payload: any, before: responseCallback | undefined, ajaxOptions: any) => {
const data = (before && before.call(model, payload)) || payload;
return assign(ajaxOptions || {}, { data });
}

const handleResponse = (model: Model, response: JSONValue, after: responseCallback | undefined) => {
if (after && !model.isDestroyed) {
return after.call(model, response);
}

return response;
}
40 changes: 29 additions & 11 deletions addon/utils/member-action.ts
Expand Up @@ -2,33 +2,51 @@ import { assign } from '@ember/polyfills';
import Model from 'ember-data/model';
import { Value as JSONValue } from 'json-typescript';
import { _getModelClass, _getModelName, _getStoreFromRecord, buildOperationUrl } from './build-url';
import { EmberDataRequestType, Hook, HTTPVerb, strictifyHttpVerb } from './types';
import { EmberDataRequestType, Hook, HTTPVerb, responseCallback, strictifyHttpVerb } from './types';

export interface InstanceOperationOptions<IN, OUT> {
type?: HTTPVerb;
path: string;
urlType?: EmberDataRequestType;
ajaxOptions?: any;
before?: Hook<IN, any>;
after?: Hook<any, OUT>;
before?: responseCallback;
after?: responseCallback;
}

export default function instanceOp<IN = any, OUT = any>(options: InstanceOperationOptions<IN, OUT>) {
return function runInstanceOp(this: Model, payload: IN): Promise<OUT> {
const {
ajaxOptions,
path,
before,
after,
type = 'put',
urlType = 'updateRecord'
}: InstanceOperationOptions<IN, OUT> = options;

const recordClass = _getModelClass(this);
const modelName = _getModelName(recordClass);
const store = _getStoreFromRecord(this);
const { ajaxOptions, path, before, after, type = 'put', urlType = 'updateRecord' } = options;
const requestType: HTTPVerb = strictifyHttpVerb(type);
const adapter = store.adapterFor(modelName);
const fullUrl = buildOperationUrl(this, path, urlType);
const data = (before && before.call(this, payload)) || payload;
return adapter.ajax(fullUrl, requestType, assign(ajaxOptions || {}, { data })).then((response: JSONValue) => {
if (after && !this.isDestroyed) {
return after.call(this, response);
}
const requestOptions = combineOptions(this, payload, before, ajaxOptions);

return response;
});
return adapter
.ajax(fullUrl, requestType, requestOptions)
.then((response: JSONValue) => handleResponse(this, response, after));
};
}

const combineOptions = (model: Model, payload: any, before: responseCallback | undefined, ajaxOptions: any) => {
const data = (before && before.call(model, payload)) || payload;
return assign(ajaxOptions || {}, { data });
}

const handleResponse = (model: Model, response: JSONValue, after: responseCallback | undefined) => {
if (after && !model.isDestroyed) {
return after.call(model, response);
}

return response;
}
57 changes: 45 additions & 12 deletions addon/utils/serialize-and-push.ts
Expand Up @@ -9,16 +9,18 @@ import { _getModelClass, _getModelName, _getStoreFromRecord } from './build-url'
function isJsonApi(raw: any): raw is JSONApiDoc {
return raw.jsonapi && raw.jsonapi.version;
}

function isDocWithData(doc: any): doc is DocWithData {
return isJsonApi(doc) && ['object', 'array'].indexOf(typeOf((doc as DocWithData).data)) >= 0;
}

export default function serializeAndPush(this: Model, response: any) {
if (!isDocWithData(response)) {

// tslint:disable-next-line:no-console
console.warn(
'serializeAndPush may only be used with a JSON API document. Ignoring response. ' +
'Document must have a mandatory JSON API object. See https://jsonapi.org/format/#document-jsonapi-object.'
'Document must have a mandatory JSON API object. See https://jsonapi.org/format/#document-jsonapi-object.'
);
return response;
}
Expand All @@ -27,19 +29,50 @@ export default function serializeAndPush(this: Model, response: any) {
const modelName = _getModelName(recordClass);
const store = _getStoreFromRecord(this);
const serializer: JSONSerializer = store.serializerFor(modelName as keyof SerializerRegistry);
let normalized: {};
const normalized = normalizedResponse(this, response, serializer);

return store.push(normalized);
}

const normalizedResponse = (model: Model, response: any, serializer: JSONSerializer) => {
if (isArray(response.data)) {
const doc = response as CollectionResourceDoc;
normalized = serializer.normalizeArrayResponse(store, recordClass as any, doc, null as any, 'findAll');
return normalizedResponseForArray(
model,
serializer,
response as CollectionResourceDoc
);
} else {
const doc = response as SingleResourceDoc;
normalized = serializer.normalizeSingleResponse(
store,
recordClass as any,
doc,
`${doc.data.id || '(unknown)'}`,
'findRecord'
return normalizedSingleResponse(
model,
serializer,
response as SingleResourceDoc
);
}
return store.push(normalized);
}

const normalizedResponseForArray = (model: Model, serializer: JSONSerializer, response: CollectionResourceDoc) => {
const recordClass = _getModelClass(model);
const store = _getStoreFromRecord(model);

return serializer.normalizeArrayResponse(
store,
recordClass as any,
response,
null as any,
'findAll'
);
}

const normalizedSingleResponse = (model: Model, serializer: JSONSerializer, response: SingleResourceDoc) => {
const recordClass = _getModelClass(model);
const store = _getStoreFromRecord(model);
const responseId = response.data.id || '(unknown)';

return serializer.normalizeSingleResponse(
store,
recordClass as any,
response,
responseId,
'findRecord'
);
}
4 changes: 3 additions & 1 deletion addon/utils/types.ts
@@ -1,5 +1,5 @@
import Model from 'ember-data/model';

import { Value as JSONValue } from 'json-typescript';
export type StrictHTTPVerb = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'OPTIONS' | 'HEAD';
export type HTTPVerb =
| 'GET'
Expand Down Expand Up @@ -51,3 +51,5 @@ export type EmberDataRequestType =
| 'deleteRecord';

export type Hook<IN, OUT> = (this: Model, payload: IN) => OUT;

export type responseCallback = (this: Model, response: JSONValue) => any;