import { merge } 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'; export interface InstanceOperationOptions { type?: HTTPVerb; path: string; urlType?: EmberDataRequestType; ajaxOptions?: any; before?: Hook; after?: Hook; } export default function instanceOp(options: InstanceOperationOptions) { return function runInstanceOp(this: Model, payload: IN): Promise { 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, merge(ajaxOptions || {}, { data })).then((response: JSONValue) => { if (after && !this.isDestroyed) { return after.call(this, response); } return response; }); }; }