export function updateViaAjax(payl: AjaxUpdatePayload) { const { uuid, statusBeforeError, dispatch, index } = payl; const resource = findByUuid(index, uuid); const { body, kind } = resource; let verb: "post" | "put"; let url = urlFor(kind); if (body.id) { verb = "put"; if (!SINGULAR_RESOURCE.includes(unpackUUID(payl.uuid).kind)) { url += body.id; } } else { verb = "post"; } maybeStartTracking(uuid); return axios[verb]<typeof resource.body>(url, body) .then(function (resp) { const r1 = defensiveClone(resource); const r2 = { body: defensiveClone(resp.data) }; const newTR = assign({}, r1, r2); if (isTaggedResource(newTR)) { dispatch(saveOK(newTR)); } else { throw new Error("Just saved a malformed TR."); } }) .catch(function (err: UnsafeError) { dispatch(updateNO({ err, uuid, statusBeforeError })); return Promise.reject(err); }); }
/** Shared functionality in create() and update(). */ function updateViaAjax(index: ResourceIndex, uuid: string, dispatch: Function) { let resource = findByUuid(index, uuid); let { body, kind } = resource; let verb: "post" | "put"; let url = urlFor(kind); if (body.id) { verb = "put"; url += body.id; } else { verb = "post"; } return axios[verb](url, body) .then(function (resp: HttpData<typeof resource.body>) { let r1 = defensiveClone(resource); let r2 = { body: defensiveClone(resp.data) }; let newTR = _.assign({}, r1, r2); if (isTaggedResource(newTR)) { dispatch(updateOK(newTR)); } else { throw new Error("Just saved a malformed TR."); } }) .catch(function (err: UnsafeError) { dispatch(updateNO({ err, uuid })); return Promise.reject(err); }); }