Skip to content

A platform for community discussion. Free, open, simple.

DEV: Convert `ajax` to TypeScript and type model responses with it (#45372)

Sérgio Saquetim79bd82ac9340
diff --git a/frontend/discourse-types/language-server.test.mjs b/frontend/discourse-types/language-server.test.mjs
index 2b160432c9e..99998878445 100644
--- a/frontend/discourse-types/language-server.test.mjs
+++ b/frontend/discourse-types/language-server.test.mjs
@@ -23,10 +23,10 @@ const IMPORTS = [
source: "frontend/discourse/app/lib/later.ts",
},
{
- specifier: "discourse/lib/ajax",
- binding: "{ ajax }",
- name: "ajax",
- source: "frontend/discourse/app/lib/ajax.js",
+ specifier: "discourse/lib/get-url",
+ binding: "getURL",
+ name: "getURL",
+ source: "frontend/discourse/app/lib/get-url.js",
},
{
specifier: "discourse/ui-kit/d-button",
diff --git a/frontend/discourse/admin/models/admin-dashboard.ts b/frontend/discourse/admin/models/admin-dashboard.ts
index 1264e011eb3..b742fa5bcbd 100644
--- a/frontend/discourse/admin/models/admin-dashboard.ts
+++ b/frontend/discourse/admin/models/admin-dashboard.ts
@@ -40,10 +40,9 @@ export default class AdminDashboard extends EmberObject {
data.end_date = moment(endDate).format("YYYY-MM-DD");
}
- // TODO(typescript-pending): ajax has no response generic; remove this assertion when it does.
- const json = (await ajax("/admin/dashboard.json", {
+ const json = await ajax<AdminDashboardFields>("/admin/dashboard.json", {
data,
- })) as AdminDashboardFields;
+ });
const model = AdminDashboard.create();
model.setProperties({
@@ -56,10 +55,12 @@ export default class AdminDashboard extends EmberObject {
}
static async fetchProblems(): Promise<AdminDashboard> {
- // TODO(typescript-pending): ajax has no response generic; remove this assertion when it does.
- const json = (await ajax("/admin/dashboard/problems.json", {
- type: "POST",
- })) as { problems: AdminDashboardProblem[] };
+ const json = await ajax<{ problems: AdminDashboardProblem[] }>(
+ "/admin/dashboard/problems.json",
+ {
+ type: "POST",
+ }
+ );
const model = AdminDashboard.create(json);
model.set("loaded", true);
diff --git a/frontend/discourse/admin/models/admin-user.ts b/frontend/discourse/admin/models/admin-user.ts
index 4f354ac0b2f..15bbaae1c56 100644
--- a/frontend/discourse/admin/models/admin-user.ts
+++ b/frontend/discourse/admin/models/admin-user.ts
@@ -201,10 +201,7 @@ export default class AdminUser extends User {
user_id: string | number,
opts: { raw?: boolean } | null = { raw: false }
): Promise<AdminUserDetails | AdminUser> {
- // TODO(typescript-pending): ajax has no endpoint contracts; remove when admin user responses are typed.
- const result = (await ajax(
- `/admin/users/${user_id}.json`
- )) as AdminUserDetails;
+ const result = await ajax<AdminUserDetails>(`/admin/users/${user_id}.json`);
result.loadedDetails = true;
if (Object.hasOwn(result, "groups")) {
diff --git a/frontend/discourse/admin/models/color-scheme.ts b/frontend/discourse/admin/models/color-scheme.ts
index ebca29428f0..5fc9d25ed1e 100644
--- a/frontend/discourse/admin/models/color-scheme.ts
+++ b/frontend/discourse/admin/models/color-scheme.ts
@@ -77,8 +77,7 @@ export default class ColorScheme extends EmberObject {
static async findAll(): Promise<ColorSchemes> {
const colorSchemes = ColorSchemes.create({ content: [], loading: true });
- // TODO(typescript-pending): ajax has no response generic; remove this assertion when it does.
- const all = (await ajax("/admin/color_schemes")) as ColorSchemePayload[];
+ const all = await ajax<ColorSchemePayload[]>("/admin/color_schemes");
all.forEach((colorScheme) => {
// The proxy forwards array methods to `content`.
@@ -100,10 +99,7 @@ export default class ColorScheme extends EmberObject {
}
static async find(id: number | string): Promise<ColorScheme> {
- // TODO(typescript-pending): ajax has no response generic; remove this assertion when it does.
- const json = (await ajax(
- `/admin/config/colors/${id}`
- )) as ColorSchemePayload;
+ const json = await ajax<ColorSchemePayload>(`/admin/config/colors/${id}`);
return ColorScheme.create({
id: json.id,
name: json.name,
diff --git a/frontend/discourse/admin/models/form-template.ts b/frontend/discourse/admin/models/form-template.ts
index 78b43be38ca..7d64d1ca814 100644
--- a/frontend/discourse/admin/models/form-template.ts
+++ b/frontend/discourse/admin/models/form-template.ts
@@ -57,19 +57,17 @@ export default class FormTemplate extends RestModel {
/** Resolves the plain records, not model instances. */
static async findAll(): Promise<FormTemplateFields[]> {
- // TODO(typescript-pending): ajax has no response generic; remove this assertion when it does.
- const result = (await ajax("/admin/customize/form-templates.json")) as {
+ const result = await ajax<{
form_templates: FormTemplateFields[];
- };
+ }>("/admin/customize/form-templates.json");
return result.form_templates;
}
/** Resolves the plain record, not a model instance. */
static async findById(id: number | string): Promise<FormTemplateFields> {
- // TODO(typescript-pending): ajax has no response generic; remove this assertion when it does.
- const result = (await ajax(
+ const result = await ajax<{ form_template: FormTemplateFields }>(
`/admin/customize/form-templates/${id}.json`
- )) as { form_template: FormTemplateFields };
+ );
return result.form_template;
}
diff --git a/frontend/discourse/admin/models/permalink.ts b/frontend/discourse/admin/models/permalink.ts
index bc7401909da..79c4e9cf1ac 100644
--- a/frontend/discourse/admin/models/permalink.ts
+++ b/frontend/discourse/admin/models/permalink.ts
@@ -33,10 +33,12 @@ export default interface Permalink extends PermalinkFields {}
// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
export default class Permalink extends RestModel {
static async findAll(filter?: string | null): Promise<Permalink[]> {
- // TODO(typescript-pending): ajax has no response generic; remove this assertion when it does.
- const data = (await ajax("/admin/permalinks.json", {
- data: { filter },
- })) as (PermalinkFields & RestPayload)[];
+ const data = await ajax<(PermalinkFields & RestPayload)[]>(
+ "/admin/permalinks.json",
+ {
+ data: { filter },
+ }
+ );
return data.map((p) => Permalink.create(p));
}
diff --git a/frontend/discourse/admin/models/report.ts b/frontend/discourse/admin/models/report.ts
index 2bd85688ab4..7d9153319de 100644
--- a/frontend/discourse/admin/models/report.ts
+++ b/frontend/discourse/admin/models/report.ts
@@ -373,15 +373,14 @@ export default class Report extends EmberObject {
categoryId: number | undefined,
groupId: number | undefined
): Promise<Report> {
- // TODO(typescript-pending): ajax has no response generic; remove this callback annotation when it does.
- return ajax("/admin/reports/" + type, {
+ return ajax<{ report: ReportPayload }>("/admin/reports/" + type, {
data: {
start_date: startDate,
end_date: endDate,
category_id: categoryId,
group_id: groupId,
},
- }).then((json: { report: ReportPayload }) => {
+ }).then((json) => {
// don’t fill for large multi column tables
// which are not date based
const modes = json.report.modes;
diff --git a/frontend/discourse/admin/models/site-setting.ts b/frontend/discourse/admin/models/site-setting.ts
index 54447876de4..b1de88502bd 100644
--- a/frontend/discourse/admin/models/site-setting.ts
+++ b/frontend/discourse/admin/models/site-setting.ts
@@ -183,11 +183,10 @@ export default class SiteSetting extends EmberObject {
static async findAll(
params: object = {}
): Promise<{ nameKey: string; name: string; siteSettings: SiteSetting[] }[]> {
- // TODO(typescript-pending): ajax returns untyped JSON; remove the assertion when it accepts response types.
// eslint-disable-next-line prefer-const
- let settings = (await ajax("/admin/site_settings", { data: params })) as {
+ let settings = await ajax<{
site_settings: SiteSettingWireRecord[];
- };
+ }>("/admin/site_settings", { data: params });
const categories: Record<string, SiteSetting[]> = {};
settings.site_settings.forEach(function (s) {
if (!categories[s.category]) {
diff --git a/frontend/discourse/admin/models/user-export.ts b/frontend/discourse/admin/models/user-export.ts
index 49d5645a6eb..84106c13e16 100644
--- a/frontend/discourse/admin/models/user-export.ts
+++ b/frontend/discourse/admin/models/user-export.ts
@@ -20,10 +20,9 @@ export default class UserExport extends RestModel {
static async findLatest(
user_id: number | string
): Promise<UserExport | undefined> {
- // TODO(typescript-pending): ajax has no response generic; remove this assertion when it does.
- const result = (await ajax(
- `/export_csv/latest_user_archive/${user_id}.json`
- )) as { user_export: UserExportFields & RestPayload } | null;
+ const result = await ajax<{
+ user_export: UserExportFields & RestPayload;
+ } | null>(`/export_csv/latest_user_archive/${user_id}.json`);
if (result !== null) {
return UserExport.create(result.user_export);
}
diff --git a/frontend/discourse/admin/models/version-check.ts b/frontend/discourse/admin/models/version-check.ts
index 8e334fa858a..0d08349e2e1 100644
--- a/frontend/discourse/admin/models/version-check.ts
+++ b/frontend/discourse/admin/models/version-check.ts
@@ -21,9 +21,8 @@ export default interface VersionCheck extends VersionCheckPayload {}
// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
export default class VersionCheck {
static async find(): Promise<VersionCheck> {
- // TODO(typescript-pending): ajax has no response generic; remove this assertion when it does.
return new VersionCheck(
- (await ajax("/admin/version_check")) as VersionCheckPayload
+ await ajax<VersionCheckPayload>("/admin/version_check")
);
}
diff --git a/frontend/discourse/admin/models/watched-word.ts b/frontend/discourse/admin/models/watched-word.ts
index 2bc160e28e5..137ba7a5cd6 100644
--- a/frontend/discourse/admin/models/watched-word.ts
+++ b/frontend/discourse/admin/models/watched-word.ts
@@ -64,10 +64,9 @@ export default interface WatchedWord extends WatchedWordFields {}
// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
export default class WatchedWord extends EmberObject {
static async findAll(): Promise<WatchedWordGroup[]> {
- // TODO(typescript-pending): ajax has no response generic; remove this assertion when it does.
- const list = (await ajax(
+ const list = await ajax<WatchedWordListPayload>(
"/admin/customize/watched_words.json"
- )) as WatchedWordListPayload;
+ );
const actions = {} as Record<WatchedWordAction, WatchedWord[]>;
list.actions.forEach((action) => {
diff --git a/frontend/discourse/app/lib/ajax.js b/frontend/discourse/app/lib/ajax.ts
similarity index 59%
rename from frontend/discourse/app/lib/ajax.js
rename to frontend/discourse/app/lib/ajax.ts
index 724557b926f..c30a4d35ac5 100644
--- a/frontend/discourse/app/lib/ajax.js
+++ b/frontend/discourse/app/lib/ajax.ts
@@ -10,26 +10,83 @@ import Session from "discourse/models/session";
import Site from "discourse/models/site";
import User from "discourse/models/user";
+/** jQuery request settings plus the options `ajax` handles itself. */
+export interface AjaxOptions extends Omit<
+ JQuery.AjaxSettings,
+ "url" | "success" | "error"
+> {
+ url?: string;
+ /** Resolve nothing instead of rejecting when the request never left the browser. Defaults to true. */
+ ignoreUnsent?: boolean;
+ /** Resolve `{ result, xhr }` instead of the response body. */
+ returnXHR?: boolean;
+}
+
+/** The jqXHR passed to rejection handlers, with the request details `ajax` adds. */
+export type AjaxErrorXHR = JQuery.jqXHR & {
+ jqTextStatus?: JQuery.Ajax.ErrorTextStatus;
+ requestedUrl?: string;
+};
+
+/** What an `ajax` promise rejects with. */
+export interface AjaxError {
+ jqXHR: AjaxErrorXHR;
+ textStatus: JQuery.Ajax.ErrorTextStatus;
+ errorThrown: string;
+}
+
+/**
+ * The response promise, plus `abort` to cancel the request.
+ *
+ * It resolves to `undefined` instead of the body when the response redirects
+ * the page or logs the user out.
+ */
+export type AjaxPromise<T> = Promise<T> & { abort(): void };
+
+/** The `returnXHR` result: the response body and its jqXHR. */
+export interface AjaxXHRResult<T> {
+ result: T;
+ xhr: JQuery.jqXHR;
+}
+
+/** The default response type, so JS callers and plugin declarations keep the untyped result. */
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+type UntypedResponse = any;
+
+type AjaxRequestArgs = Omit<AjaxOptions, "headers"> & {
+ headers?: Record<string, string | number | boolean | null | undefined>;
+ success?: (
+ data: unknown,
+ textStatus: JQuery.Ajax.SuccessTextStatus | JQuery.Ajax.ErrorTextStatus,
+ xhr: JQuery.jqXHR
+ ) => void;
+ error?: (
+ xhr: AjaxErrorXHR,
+ textStatus: JQuery.Ajax.ErrorTextStatus,
+ errorThrown: string
+ ) => void;
+};
+
let _trackView = false;
-let _topicId = null;
-let _trackingSessionId = null;
-let _trackingUrl = null;
-let _trackingReferrer = null;
-let _transientHeader = null;
-let _logoffCallback;
-
-export function setTransientHeader(key, value) {
+let _topicId: number | null = null;
+let _trackingSessionId: string | null = null;
+let _trackingUrl: string | null = null;
+let _trackingReferrer: string | null = null;
+let _transientHeader: { key: string; value: string } | null = null;
+let _logoffCallback: (() => void) | undefined;
+
+export function setTransientHeader(key: string, value: string) {
_transientHeader = { key, value };
}
-export function trackNextAjaxAsTopicView(topicId) {
+export function trackNextAjaxAsTopicView(topicId: number) {
_topicId = topicId;
}
export function trackNextAjaxAsPageview(
- trackingSessionId,
- trackingUrl,
- trackingReferrer
+ trackingSessionId: string | null,
+ trackingUrl: string | null,
+ trackingReferrer: string | null
) {
_trackView = true;
_trackingSessionId = trackingSessionId;
@@ -44,11 +101,11 @@ export function resetAjax() {
_trackingReferrer = null;
}
-export function setLogoffCallback(cb) {
+export function setLogoffCallback(cb: () => void) {
_logoffCallback = cb;
}
-export function handleLogoff(xhr) {
+export function handleLogoff(xhr: JQuery.jqXHR | null | undefined) {
if (xhr && xhr.getResponseHeader("Discourse-Logged-Out") && _logoffCallback) {
_logoffCallback();
return true;
@@ -56,7 +113,7 @@ export function handleLogoff(xhr) {
return false;
}
-function handleRedirect(xhr) {
+function handleRedirect(xhr: JQuery.jqXHR | null | undefined) {
if (xhr && xhr.getResponseHeader("Discourse-Xhr-Redirect")) {
DiscourseURL.redirectAbsolute(xhr.responseText, { replace: true });
return true;
@@ -64,11 +121,11 @@ function handleRedirect(xhr) {
return false;
}
-let activeCsrfRequest;
+let activeCsrfRequest: Promise<unknown> | null | undefined;
export function updateCsrfToken() {
if (!activeCsrfRequest) {
- activeCsrfRequest = ajax("/session/csrf")
+ activeCsrfRequest = ajax<{ csrf: string }>("/session/csrf")
.then((result) => Session.currentProp("csrfToken", result.csrf))
.finally(() => (activeCsrfRequest = null));
}
@@ -80,24 +137,42 @@ export function updateCsrfToken() {
Our own $.ajax method. Makes sure the .then method executes in an Ember runloop
for performance reasons. Also automatically adjusts the URL to support installs
in subfolders.
-**/
-export function ajax(...params) {
- let url, args;
- let ajaxObj;
+ `T` is the response body the caller expects; nothing checks it at runtime.
+**/
+export function ajax<T = UntypedResponse>(
+ url: string,
+ options: AjaxOptions & { returnXHR: true }
+): AjaxPromise<AjaxXHRResult<T>>;
+export function ajax<T = UntypedResponse>(
+ url: string,
+ options?: AjaxOptions
+): AjaxPromise<T>;
+export function ajax<T = UntypedResponse>(
+ options: AjaxOptions & { url: string; returnXHR: true }
+): AjaxPromise<AjaxXHRResult<T>>;
+export function ajax<T = UntypedResponse>(
+ options: AjaxOptions & { url: string }
+): AjaxPromise<T>;
+export function ajax(
+ ...params: [string | (AjaxOptions & { url?: string }), AjaxOptions?]
+): AjaxPromise<unknown> {
+ // Every supported call shape assigns both below.
+ let url!: string, args!: AjaxRequestArgs;
+ let ajaxObj: JQuery.jqXHR | undefined;
if (params.length === 1) {
if (typeof params[0] === "string") {
url = params[0];
args = {};
} else {
- args = params[0];
- url = args.url;
+ args = params[0] as AjaxRequestArgs;
+ url = args.url!;
delete args.url;
}
} else if (params.length === 2) {
- url = params[0];
- args = params[1];
+ url = params[0] as string;
+ args = params[1] as AjaxRequestArgs;
}
url = getURL(url);
@@ -108,7 +183,10 @@ export function ajax(...params) {
delete args.ignoreUnsent;
}
- function performAjax(resolve, reject) {
+ function performAjax(
+ resolve: (value?: unknown) => void,
+ reject: (reason: AjaxError) => void
+ ) {
args.headers = args.headers || {};
if (User.current()) {
@@ -194,7 +272,7 @@ export function ajax(...params) {
// If it's a parser error, don't reject
if (xhr.status === 200) {
- return args.success(
+ return args.success!(
xhr.responseJSON ?? xhr.responseText,
textStatus,
xhr
@@ -230,10 +308,10 @@ export function ajax(...params) {
args.headers["Discourse-Script"] = true;
}
- ajaxObj = $.ajax(url, args);
+ ajaxObj = $.ajax(url, args as JQuery.AjaxSettings);
}
- let promise;
+ let promise: AjaxPromise<unknown>;
// For cached pages we strip out CSRF tokens, need to round trip to server prior to sending the
// request (bypass for GET, not needed)
@@ -245,9 +323,9 @@ export function ajax(...params) {
) {
promise = new Promise((resolve, reject) => {
updateCsrfToken().then(() => performAjax(resolve, reject), reject);
- });
+ }) as AjaxPromise<unknown>;
} else {
- promise = new Promise(performAjax);
+ promise = new Promise(performAjax) as AjaxPromise<unknown>;
}
promise.abort = () => {
diff --git a/frontend/discourse/app/models/action-summary.ts b/frontend/discourse/app/models/action-summary.ts
index 1b8bab0c270..2d67b4900e1 100644
--- a/frontend/discourse/app/models/action-summary.ts
+++ b/frontend/discourse/app/models/action-summary.ts
@@ -78,25 +78,19 @@ export default class ActionSummary extends RestModel {
});
// Create our post action
- // TODO(typescript-pending): ajax has no typed returnXHR response; remove when it does.
- return (
- ajax("/post_actions", {
- type: "POST",
- data: {
- id: this.flagTopic ? this.get("flagTopic.id") : post.get("id"),
- post_action_type_id: this.id,
- message: opts.message,
- is_warning: opts.isWarning,
- take_action: opts.takeAction,
- queue_for_review: opts.queue_for_review,
- flag_topic: this.flagTopic ? true : false,
- },
- returnXHR: true,
- }) as Promise<{
- result: unknown;
- xhr: Pick<XMLHttpRequest, "getResponseHeader">;
- }>
- )
+ return ajax<unknown>("/post_actions", {
+ type: "POST",
+ data: {
+ id: this.flagTopic ? this.get("flagTopic.id") : post.get("id"),
+ post_action_type_id: this.id,
+ message: opts.message,
+ is_warning: opts.isWarning,
+ take_action: opts.takeAction,
+ queue_for_review: opts.queue_for_review,
+ flag_topic: this.flagTopic ? true : false,
+ },
+ returnXHR: true,
+ })
.then((data): { acted: true; remaining: number; max: number } => {
if (!this.flagTopic) {
// Topic flag actions skip this post-only refresh.
diff --git a/frontend/discourse/app/models/category-list.ts b/frontend/discourse/app/models/category-list.ts
index 8b2e3d6333e..68e69908c42 100644
--- a/frontend/discourse/app/models/category-list.ts
+++ b/frontend/discourse/app/models/category-list.ts
@@ -275,10 +275,9 @@ export default class CategoryList extends LegacyArrayLikeObject<Category> {
}),
};
- // TODO(typescript-pending): ajax does not publish response types; remove the assertion when its response is generic.
- const result = (await ajax("/categories.json", {
+ const result = await ajax<CategoryListEnvelope>("/categories.json", {
data,
- })) as CategoryListEnvelope;
+ });
this.page = nextPage;
diff --git a/frontend/discourse/app/models/category.ts b/frontend/discourse/app/models/category.ts
index dcca92c4e19..71f565d7f3a 100644
--- a/frontend/discourse/app/models/category.ts
+++ b/frontend/discourse/app/models/category.ts
@@ -5,7 +5,7 @@ import { dependentKeyCompat } from "@ember/object/compat";
import { trackedObject } from "@ember/reactive/collections";
import { service } from "@ember/service";
import { compare } from "@ember/utils";
-import { ajax } from "discourse/lib/ajax";
+import { ajax, type AjaxError } from "discourse/lib/ajax";
import {
addUniqueValueToArray,
removeValueFromArray,
@@ -458,10 +458,9 @@ export default class Category extends RestModel {
data.include_permissions = true;
}
- // TODO(typescript-pending): ajax does not type response payloads yet.
- const result = (await ajax("/categories/find", { data })) as {
+ const result = await ajax<{
categories: CategoryFields[];
- };
+ }>("/categories/find", { data });
const categories = result["categories"].map(
(category: CategoryFields | Category) => {
@@ -481,10 +480,12 @@ export default class Category extends RestModel {
static async asyncFindBySlugPathWithID(
slugPathWithID: string
): Promise<Category | undefined> {
- // TODO(typescript-pending): ajax does not type response payloads yet.
- const result = (await ajax("/categories/find", {
- data: { slug_path_with_id: slugPathWithID },
- })) as { categories: CategoryFields[] };
+ const result = await ajax<{ categories: CategoryFields[] }>(
+ "/categories/find",
+ {
+ data: { slug_path_with_id: slugPathWithID },
+ }
+ );
const categories = result["categories"].map((category) =>
Site.current().updateCategory(category)
@@ -1329,17 +1330,15 @@ export default class Category extends RestModel {
const categoryMultiCache = new MultiCache(async (ids: number[]) => {
try {
- // TODO(typescript-pending): ajax does not type response payloads yet.
- const { categories } = (await ajax("/categories/find", {
- data: { ids },
- })) as { categories: CategoryFields[] };
+ const { categories } = await ajax<{ categories: CategoryFields[] }>(
+ "/categories/find",
+ {
+ data: { ids },
+ }
+ );
return new Map(categories.map((category) => [category.id, category]));
} catch (error) {
- // TODO(typescript-pending): ajax rejects with its jqXHR wrapper; remove when errors are typed.
- if (
- (error as { jqXHR?: { status?: number } }).jqXHR?.status ===
- HTTP_NOT_FOUND
- ) {
+ if ((error as AjaxError).jqXHR?.status === HTTP_NOT_FOUND) {
return new Map();
}
diff --git a/frontend/discourse/app/models/composer.ts b/frontend/discourse/app/models/composer.ts
index 344c8323586..5e04598ec61 100644
--- a/frontend/discourse/app/models/composer.ts
+++ b/frontend/discourse/app/models/composer.ts
@@ -8,6 +8,7 @@ import { isEmpty } from "@ember/utils";
import { on } from "@ember-decorators/object";
import { Promise } from "rsvp";
import type DialogService from "discourse/dialog-holder/services/dialog";
+import type { AjaxError } from "discourse/lib/ajax";
import { extractError, throwAjaxError } from "discourse/lib/ajax-error";
import { tinyAvatar } from "discourse/lib/avatar-utils";
import deprecated from "discourse/lib/deprecated";
@@ -1550,90 +1551,72 @@ export default class Composer extends RestModel {
const draftSequence = this.draftSequence;
this.set("draftSequence", this.draftSequence! + 1);
- return (
- Draft.save(
- this.draftKey!,
- draftSequence!,
- this.serializeDraftData(),
- this.messageBus.clientId,
- { forceSave: this.draftForceSave }
- )
- .then((result) => {
- if ("draft_sequence" in result) {
- this.set("draftSequence", result.draft_sequence);
- }
- if (result.conflict_user) {
- this.setProperties({
- draftStatus: i18n("composer.edit_conflict"),
- draftConflictUser: result.conflict_user,
- });
- } else {
- this.setProperties({
- draftStatus: null,
- draftConflictUser: null,
- draftForceSave: false,
- });
- }
+ return Draft.save(
+ this.draftKey!,
+ draftSequence!,
+ this.serializeDraftData(),
+ this.messageBus.clientId,
+ { forceSave: this.draftForceSave }
+ )
+ .then((result) => {
+ if ("draft_sequence" in result) {
+ this.set("draftSequence", result.draft_sequence);
+ }
+ if (result.conflict_user) {
+ this.setProperties({
+ draftStatus: i18n("composer.edit_conflict"),
+ draftConflictUser: result.conflict_user,
+ });
+ } else {
+ this.setProperties({
+ draftStatus: null,
+ draftConflictUser: null,
+ draftForceSave: false,
+ });
+ }
- return result;
- })
- // TODO(typescript-pending): ajax rejection values have no typed envelope; use its error contract when ajax is typed.
- .catch(
- (
- e:
- | {
- jqXHR?: {
- status?: number;
- responseJSON?: {
- errors?: string[];
- extras?: { description?: string };
- };
- };
- }
- | null
- | undefined
- ) => {
- let draftStatus;
- const xhr = e && e.jqXHR;
-
- if (
- xhr &&
- xhr.status === 409 &&
- xhr.responseJSON &&
- xhr.responseJSON.errors &&
- xhr.responseJSON.errors.length
- ) {
- const json = e!.jqXHR!.responseJSON!;
- draftStatus = json.errors![0];
-
- if (json.extras?.description) {
- this.dialog.alert({
- message: json.extras.description,
- buttons: [
- {
- label: i18n("composer.reload"),
- class: "btn-primary",
- action: () => window.location.reload(),
- },
- {
- label: i18n("composer.ignore"),
- class: "btn-default",
- action: () => this.set("draftForceSave", true),
- },
- ],
- });
- }
- }
- this.setProperties({
- draftStatus: draftStatus || i18n("composer.drafts_offline"),
- draftConflictUser: null,
+ return result;
+ })
+ .catch((e: AjaxError | null | undefined) => {
+ let draftStatus;
+ const xhr = e && e.jqXHR;
+
+ if (
+ xhr &&
+ xhr.status === 409 &&
+ xhr.responseJSON &&
+ xhr.responseJSON.errors &&
+ xhr.responseJSON.errors.length
+ ) {
+ const json = e!.jqXHR!.responseJSON!;
+ draftStatus = json.errors![0];
+
+ if (json.extras?.description) {
+ this.dialog.alert({
+ message: json.extras.description,
+ buttons: [
+ {
+ label: i18n("composer.reload"),
+ class: "btn-primary",
+ action: () => window.location.reload(),
+ },
+ {
+ label: i18n("composer.ignore"),
+ class: "btn-default",
+ action: () => this.set("draftForceSave", true),
+ },
+ ],
});
}
- )
- .finally(() => {
- this.set("draftSaving", false);
- })
- );
+ }
+ this.setProperties({
+ draftStatus: draftStatus || i18n("composer.drafts_offline"),
+ draftConflictUser: null,
+ });
+ })
+ .finally(() => {
+ this.set("draftSaving", false);
+ });
}
customizationFor(type: string) {
diff --git a/frontend/discourse/app/models/form-template.ts b/frontend/discourse/app/models/form-template.ts
index be3e3c2ba7d..7bea6d58746 100644
--- a/frontend/discourse/app/models/form-template.ts
+++ b/frontend/discourse/app/models/form-template.ts
@@ -10,10 +10,9 @@ export interface FormTemplatePayload {
export default class FormTemplate extends RestModel {
static async findAll(): Promise<FormTemplatePayload[]> {
- // TODO(typescript-pending): remove the response assertion when ajax supports typed payloads.
- const result = (await ajax("/form-templates.json")) as {
+ const result = await ajax<{
form_templates: FormTemplatePayload[];
- };
+ }>("/form-templates.json");
return result.form_templates;
}
diff --git a/frontend/discourse/app/models/invite.ts b/frontend/discourse/app/models/invite.ts
index 70dd24b3452..f31ff1e7d66 100644
--- a/frontend/discourse/app/models/invite.ts
+++ b/frontend/discourse/app/models/invite.ts
@@ -90,13 +90,11 @@ export default class Invite extends EmberObject {
}
data.offset = offset || 0;
- // TODO(typescript-pending): ajax has no endpoint response types; remove the assertion when generic.
- const result = (await ajax(
- userPath(`${user.username_lower}/invited.json`),
- {
- data,
- }
- )) as Omit<InvitedFields, "invites"> & { invites: InviteCreateAttrs[] };
+ const result = await ajax<
+ Omit<InvitedFields, "invites"> & { invites: InviteCreateAttrs[] }
+ >(userPath(`${user.username_lower}/invited.json`), {
+ data,
+ });
result.invites = trackedArray(result.invites.map((i) => Invite.create(i)));
@@ -157,13 +155,13 @@ export default class Invite extends EmberObject {
save(data: object) {
const promise = this.id
- ? ajax(`/invites/${this.id}`, { type: "PUT", data })
- : ajax("/invites", { type: "POST", data });
+ ? ajax<Partial<InviteFields>>(`/invites/${this.id}`, {
+ type: "PUT",
+ data,
+ })
+ : ajax<Partial<InviteFields>>("/invites", { type: "POST", data });
- // TODO(typescript-pending): ajax has no endpoint response types; remove the callback annotation when generic.
- return promise.then((result: Partial<InviteFields>) =>
- this.setProperties(result)
- );
+ return promise.then((result) => this.setProperties(result));
}
/** Deletes the invite remotely rather than scheduling Ember destruction. */
diff --git a/frontend/discourse/app/models/reviewable.ts b/frontend/discourse/app/models/reviewable.ts
index e74bd0e7e0d..6266e5b0604 100644
--- a/frontend/discourse/app/models/reviewable.ts
+++ b/frontend/discourse/app/models/reviewable.ts
@@ -416,11 +416,10 @@ export default class Reviewable extends RestModel {
// eslint-disable-next-line prefer-const
let adapter = this.store.adapterFor("reviewable");
- // TODO(typescript-pending): ajax has no endpoint response types; remove the callback annotation when generic.
- return ajax(
+ return ajax<Partial<ReviewableFields>>(
`/review/${this.id}?version=${this.version}`,
adapter.getPayload("PUT", { reviewable: updates })
- ).then((updated: Partial<ReviewableFields>) => {
+ ).then((updated) => {
updated.payload = Object.assign(
{},
this.payload || {},
diff --git a/frontend/discourse/app/models/topic-list.ts b/frontend/discourse/app/models/topic-list.ts
index 65ef2dbc1c9..b58838f6eae 100644
--- a/frontend/discourse/app/models/topic-list.ts
+++ b/frontend/discourse/app/models/topic-list.ts
@@ -346,9 +346,8 @@ export default class TopicList extends RestModel {
this.set("loadingMore", true);
- // TODO(typescript-pending): ajax does not publish response types; remove the payload annotation when its response is generic.
- return ajax({ url: moreUrl }).then(
- async (result: TopicListEnvelope | undefined) => {
+ return ajax<TopicListEnvelope | undefined>({ url: moreUrl }).then(
+ async (result) => {
let topicsAdded = 0;
if (result) {
@@ -384,11 +383,10 @@ export default class TopicList extends RestModel {
try {
const url = `/${this.filter}.json?topic_ids=${topic_ids.join(",")}`;
- // TODO(typescript-pending): ajax does not publish response types; remove the assertion when its response is generic.
- const result = (await ajax({
+ const result = await ajax<TopicListEnvelope>({
url,
data: this.params,
- })) as TopicListEnvelope;
+ });
// refresh dupes
removeValuesFromArray(
diff --git a/frontend/discourse/app/models/user-posts-stream.ts b/frontend/discourse/app/models/user-posts-stream.ts
index e5c15f90ad0..e0ceb92d6c5 100644
--- a/frontend/discourse/app/models/user-posts-stream.ts
+++ b/frontend/discourse/app/models/user-posts-stream.ts
@@ -55,11 +55,9 @@ export default class UserPostsStream extends EmberObject {
this.loading = true;
try {
- // TODO(typescript-pending): ajax lacks response types; remove the cast when this endpoint can be typed by ajax.
- const result = (await ajax(this.url)) as
- | (UserActionFields & Record<string, unknown>)[]
- | null
- | undefined;
+ const result = await ajax<
+ (UserActionFields & Record<string, unknown>)[] | null | undefined
+ >(this.url);
if (result) {
const posts = result.map((post) => UserAction.create(post));
this.content.push(...posts);
diff --git a/frontend/discourse/app/models/user-stream.ts b/frontend/discourse/app/models/user-stream.ts
index cdf489c4bb7..3e9cf7e5e20 100644
--- a/frontend/discourse/app/models/user-stream.ts
+++ b/frontend/discourse/app/models/user-stream.ts
@@ -123,14 +123,14 @@ export default class UserStream extends RestModel {
this.loading = true;
try {
- // TODO(typescript-pending): ajax lacks response types; remove the cast when this endpoint can be typed by ajax.
- const result = (await ajax(findUrl)) as
+ const result = await ajax<
| {
user_actions?: (UserActionFields & Record<string, unknown>)[];
categories?: CategoryFields[];
}
| null
- | undefined;
+ | undefined
+ >(findUrl);
if (result && result.user_actions) {
const copy: UserAction[] = [];
diff --git a/frontend/discourse/app/models/user.ts b/frontend/discourse/app/models/user.ts
index e5e754fe531..43ec11a2b26 100644
--- a/frontend/discourse/app/models/user.ts
+++ b/frontend/discourse/app/models/user.ts
@@ -1740,10 +1740,9 @@ export default class User extends RestModel.extend(Evented) {
}
async loadUserAction(id: number) {
- // TODO(typescript-pending): ajax has no endpoint response contracts; remove when user-action responses are typed.
- const result = (await ajax(`/user_actions/${id}.json`)) as {
+ const result = await ajax<{
user_action?: UserActionFields & RestPayload;
- };
+ }>(`/user_actions/${id}.json`);
if (!result?.user_action) {
return;
@@ -1991,57 +1990,54 @@ export default class User extends RestModel.extend(Evented) {
"service:store"
) as StoreService;
- return ajax(userPath(`${this.username_lower}/summary.json`)).then(
- // TODO(typescript-pending): ajax has no endpoint response contracts; remove when summary responses are typed.
- (json: {
- topics: RestModelAttrs<Topic>[];
- user_summary: Omit<UserSummary, "badges"> & {
- badges?: { badge_id: number; count: number }[];
- };
- }) => {
- const summary = json.user_summary;
- const topicMap: Record<number, Topic> = {};
- const badgeMap: Record<number, UserBadgeModel> = {};
-
- json.topics.forEach(
- (t) => (topicMap[t.id!] = store.createRecord("topic", t))
- );
- (Badge.createFromJson(json) as UserBadgeModel[]).forEach(
- (b) => (badgeMap[b.id] = b)
- );
+ return ajax<{
+ topics: RestModelAttrs<Topic>[];
+ user_summary: Omit<UserSummary, "badges"> & {
+ badges?: { badge_id: number; count: number }[];
+ };
+ }>(userPath(`${this.username_lower}/summary.json`)).then((json) => {
+ const summary = json.user_summary;
+ const topicMap: Record<number, Topic> = {};
+ const badgeMap: Record<number, UserBadgeModel> = {};
- summary.topics = summary.topic_ids.map((id) => topicMap[id]);
+ json.topics.forEach(
+ (t) => (topicMap[t.id!] = store.createRecord("topic", t))
+ );
+ (Badge.createFromJson(json) as UserBadgeModel[]).forEach(
+ (b) => (badgeMap[b.id] = b)
+ );
- summary.replies.forEach((r) => {
- r.topic = topicMap[r.topic_id];
- r.url = r.topic.urlForPostNumber(r.post_number);
- r.createdAt = new Date(r.created_at);
- });
+ summary.topics = summary.topic_ids.map((id) => topicMap[id]);
- summary.links.forEach((l) => {
- l.topic = topicMap[l.topic_id];
- l.post_url = l.topic.urlForPostNumber(l.post_number);
- });
+ summary.replies.forEach((r) => {
+ r.topic = topicMap[r.topic_id];
+ r.url = r.topic.urlForPostNumber(r.post_number);
+ r.createdAt = new Date(r.created_at);
+ });
- if (summary.badges) {
- (summary as UserSummary).badges = summary.badges.map((ub) => {
- const badge = badgeMap[ub.badge_id];
- badge.count = ub.count;
- return badge;
- });
- }
+ summary.links.forEach((l) => {
+ l.topic = topicMap[l.topic_id];
+ l.post_url = l.topic.urlForPostNumber(l.post_number);
+ });
- if (summary.top_categories) {
- summary.top_categories.forEach((c) => {
- if (c.parent_category_id) {
- c.parentCategory = Category.findById(c.parent_category_id);
- }
- });
- }
+ if (summary.badges) {
+ (summary as UserSummary).badges = summary.badges.map((ub) => {
+ const badge = badgeMap[ub.badge_id];
+ badge.count = ub.count;
+ return badge;
+ });
+ }
- return summary as UserSummary;
+ if (summary.top_categories) {
+ summary.top_categories.forEach((c) => {
+ if (c.parent_category_id) {
+ c.parentCategory = Category.findById(c.parent_category_id);
+ }
+ });
}
- );
+
+ return summary as UserSummary;
+ });
}
canManageGroup(group: Group) {
diff --git a/lib/middleware/request_tracker.rb b/lib/middleware/request_tracker.rb
index fd4a7ef3999..631cfb829e6 100644
--- a/lib/middleware/request_tracker.rb
+++ b/lib/middleware/request_tracker.rb
@@ -588,7 +588,7 @@ class Middleware::RequestTracker
is_html_request = headers["Content-Type"]&.include?("text/html")
is_ajax_request = request.xhr?
- # This Discourse-Track-View request header is set in `lib/ajax.js`,
+ # This Discourse-Track-View request header is set in `lib/ajax.ts`,
# whenever the user navigates between Ember routes, to indicate a
# browser page view.
env_track_view = env["HTTP_DISCOURSE_TRACK_VIEW"]