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
Changes from 1 commit
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
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