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 4 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) === '/';
}
46 changes: 30 additions & 16 deletions addon/utils/collection-action.ts
Expand Up @@ -14,24 +14,38 @@ export interface CollectionOperationOptions<IN, OUT> {
}

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);
return async function runCollectionOp(this: Model, payload: IN): Promise<OUT> {
Rxbsxn marked this conversation as resolved.
Show resolved Hide resolved
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;
});
const response = await adapter.ajax(fullUrl, requestType, requestOptions);
return handleResponse(this, response, after);
};
}

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

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

return response;
}
35 changes: 26 additions & 9 deletions addon/utils/member-action.ts
Expand Up @@ -14,21 +14,38 @@ export interface InstanceOperationOptions<IN, OUT> {
}

export default function instanceOp<IN = any, OUT = any>(options: InstanceOperationOptions<IN, OUT>) {
return function runInstanceOp(this: Model, payload: IN): Promise<OUT> {
return async function runInstanceOp(this: Model, payload: IN): Promise<OUT> {
const {
ajaxOptions,
path,
before,
after,
type = 'put',
urlType = 'updateRecord'
} = 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;
});
const response: JSONValue = await adapter.ajax(fullUrl, requestType, requestOptions);
return handleResponse(this, response, after)
};
}

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

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

return response;
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What do you think about using a type for before and after that makes it clear that they are functions that should expect Model as the value for this and response as an argument? I think that might make the type definitions a bit more accurate (and useful!)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will try to use that type, it will be much more readable

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'
);
}