Create a goal metric

Creates and adds a goal metric to a specified goal. Note that this replaces an existing goal metric if one already exists.

Script asana Verified

by hugo697 ยท 10/31/2023

The script

Submitted by hugo697 Typescript (fetch-only)
Verified 383 days ago
1
type Asana = {
2
  token: string;
3
};
4
/**
5
 * Create a goal metric
6
 * Creates and adds a goal metric to a specified goal. Note that this replaces an existing goal metric if one already exists.
7
 */
8
export async function main(
9
  auth: Asana,
10
  goal_gid: string,
11
  opt_pretty: string | undefined,
12
  opt_fields: string | undefined,
13
  body: {
14
    data?: { gid?: string; resource_type?: string; [k: string]: unknown } & {
15
      currency_code?: string;
16
      current_display_value?: string;
17
      current_number_value?: number;
18
      initial_number_value?: number;
19
      precision?: number;
20
      progress_source?:
21
        | "manual"
22
        | "subgoal_progress"
23
        | "project_task_completion"
24
        | "project_milestone_completion"
25
        | "external";
26
      resource_subtype?: "number";
27
      target_number_value?: number;
28
      unit?: "none" | "currency" | "percentage";
29
      [k: string]: unknown;
30
    };
31
    [k: string]: unknown;
32
  }
33
) {
34
  const url = new URL(
35
    `https://app.asana.com/api/1.0/goals/${goal_gid}/setMetric`
36
  );
37
  for (const [k, v] of [
38
    ["opt_pretty", opt_pretty],
39
    ["opt_fields", opt_fields],
40
  ]) {
41
    if (v !== undefined && v !== "") {
42
      url.searchParams.append(k, v);
43
    }
44
  }
45
  const response = await fetch(url, {
46
    method: "POST",
47
    headers: {
48
      "Content-Type": "application/json",
49
      Authorization: "Bearer " + auth.token,
50
    },
51
    body: JSON.stringify(body),
52
  });
53
  if (!response.ok) {
54
    const text = await response.text();
55
    throw new Error(`${response.status} ${text}`);
56
  }
57
  return await response.json();
58
}
59