GitHubBeitragen in GitHub: Online bearbeiten

JavaScript Referenz

Skriptvariablen für geänderte Entitätsquelle

args.Author - ein Objekt, das den Modifikator darstellt

args.Current - Dies ist ein Objekt, das den aktuellen Zustand der modifizierten Entität darstellt.

// Get the name of the modified entity
const name = args.Current.Name;

// Most fields listed at /api/v1/Index/meta can be used
//
// Custom fields can be accessed directly by their name:
const cfValue1 = args.Current.Category;
const cfValue2 = args.Current["Expected Risk"];

// All own simple fields like Name, Effort, Description should be available
// Reference fields like Project have only a limited number of fields: Id and Name
const projectName = args.Current.Project.Name;
// So this WILL NOT work:
args.Current.Project.EntityState.Name;
// Collections ARE NOT available so this WILL NOT work:
args.Current.Bugs.Count

// If the script requires additional data, it can be retrieved through call to "targetprocess/api/v2" service.

args.Modification - eine Zeichenfolge, die die Art der letzten Änderung angibt. Verfügbare Werte sind: "Erstellt", "Aktualisiert", "Gelöscht"

args.Previous - ein Objekt, das den Zustand der Entität vor der Änderung darstellt. Wenn args.Modification auf "Created" steht, wird dieses Feld auf null

const originalEffort = args.Previous.Effort;

args.ResourceId - eine Nummer, die die ID der geänderten Entität enthält

args.ResourceType - eine Zeichenfolge, die den Typ der geänderten Entität angibt, z. B. "UserStory", "Bug", "TeamAssignment".

args.ChangedFields - ein Array von Strings, das die Namen der Felder enthält, die im Rahmen des Ereignisses, das die Regel ausgelöst hat, geändert wurden.

// Check whether the name of the User Story was modified:
const wasNameChanged = args.ChangedFields.contains("Name");

Skriptvariablen für eingehende Web-Hook-Quellen

args.headers - ein Objekt, das den Header einer eingehenden http-Anfrage darstellt.

args.body - ein Objekt, das den Körper einer eingehenden http-Anfrage darstellt.

const branch = args.body.object_attributes.ref;

Abfrage der Targetprocess-API

context.getService("targetprocess/apiv2") - Ein Aufruf dieser Funktion gibt einen Dienst zurück, der es dem Skript ermöglicht, Abfragen an die Targetprocess API v2 zu stellen.
require("targetprocess/api/v2") - der Dienst kann auch auf diese Weise abgerufen werden.

Hier ein Beispiel für das Abrufen von 100 Fehlern, sortiert nach Name für eine geänderte User Story:

const userStoryId = args.ResourceId;

const api = context.getService("targetprocess/api/v2");

// `querySpec` here mirrors the shape of API v2 query parameters,
// such as `select`, `where`, `result`, etc.
// See https://dev.targetprocess.com/docs/api-v2-overview for details
const querySpec = {
    select: "{id, name}",
    where: "userStory.id == " + userStoryId,
    take: 100,
    orderBy: "name"
};

// `queryAsync` function makes HTTP call to tpondemand.com/api/v2/bugs
const bugs = await api.queryAsync(
  // The first argument is the name of Targetprocess entities to query
  "bug",
  // The second is our query definition — filters, fields to return, etc.
  querySpec);

// At this point, `bugs` is an array of objects with the fields specified in `querySpec.select`, e.g.
// [ 
//   {id: 1, name: "First Bug"},
//   {id: 2, name: "Second Bug"}
// ]

const firstBugName = bugs[0].name;

Der Targetprocess-API-Client kann auch einzelne Ressourcen mit der Methode getByIdAsync abfragen

const api = context.getService("targetprocess/api/v2");
const userStoryDetails = await api.getByIdAsync(
  // Return details of UserStory#42
  "UserStory", 42,
  // 3rd parameter acts like `select` in API v2 query and lets the script specify which fields of resource to fetch
  {select: "{id,name,bugsCount:Bugs.Count}"});

if (!userStoryDetails) {
  console.error("There is no such User Story");
} else {
  console.log(userStoryDetails.bugsCount);
}

Durchführung von HTTP Anfragen

context.getService("http") - ein Aufruf dieser Funktion gibt einen Dienst zurück, mit dem das Skript HTTP Anfragen an externe APIs stellen kann.
require("http") - Der Dienst kann auch auf diese Weise abgerufen werden.

HTTP dienst unterstützt die folgenden Methoden:

  • http.getAsync()
  • http.postAsync()
  • http.sendAsync()
  • http.putAsync()
  • http.deleteAsync()
  • http.patchAsync()

Hier ist ein Beispiel, das Daten von einer API des Anbieters 3rd abruft.

const http = context.getService('http');

const firstResponse = await http.getAsync('https://reqres.in/api/users');
// Response object contains the body of HTTP response directly.
console.log(firstResponse);

// Script can also pass HTTP headers
const secondResponse = await http.getAsync(
  'https://reqres.in/api/users',
  {
    headers: {
      'Authorization': 'Scheme Token'
    }
  }
);

console.log(secondResponse);

Ein weiteres Beispiel mit der Postabfrage an einen Webhook URL.

const http = require('http');

const response = await http.postAsync('https://webhook.site/123456', {
  headers: {
    'Some-header-key': 'some-value'
  },
  body: {
    "firstName": "John",
    "lastName": "Doe"
  }
});

Beispiel für die PUT-Methode.

const http = context.getService("http")
 
const res = await http.putAsync("http://dummy.restapiexample.com/api/v1/update/21");

DELETE-Methode.

const http = require('http');

const response = await http.deleteAsync('https://test.tpondemand.com/api/v1/UserStories/12345?token=1234567890==');

Zugriff auf HTTP Antwort-Header

Einige Integrationen übermitteln die erforderlichen Informationen in den Kopfzeilen von HTTP. Derzeit gibt es eine Möglichkeit, über JS-Automatisierungsregeln auf sie zuzugreifen.
sendAsync methode wurde dem Dienst http hinzugefügt. Diese Methode gibt ein result -Objekt zurück, das Zugriff auf Antwort-Interna bietet, z. B. B. statusCode, kopfzeilen.

const http = require('http');

const response = await http.sendAsync('https://reqres.in/api/users', {
  method: 'POST',
  body: {
    "name": "morpheus",
    "job": "leader"
  }
});

console.log(response.statusCode); // Returns response status code as a number, e.g. 200
console.log(response.headers); // Returns all response headers as an object
console.log(response.headers['content-type']); // Returns particular response header value as a string value
console.log(response.body); // Returns response body as a string value

📘 Weiße Liste für Anfragen von Automatisierungsregeln

Wenn Sie Abfragen des Dienstes für Automatisierungsregeln auf Ihrer Proxy-Firewall zulassen müssen, finden Sie die Liste der IP-Adressen, die in die Whitelist aufgenommen werden müssen, unter Apptio Community Targetprocess public IPs range.

Aktionsbefehle

Dieser Abschnitt beschreibt das Format der Befehle, die von JavaScript Aktionsblöcken zurückgegeben werden können. Das Befehlsformat wird mit der Syntax TypeScript beschrieben, und auf der Registerkarte "Beispiel" werden funktionierende Befehlsbeispiele angezeigt.

targetprocess:CreateResource ermöglicht die Erstellung einer neuen Targetprocess-Entität, wie z.B. Task oder Project.

{
  command: "targetprocess:CreateResource",
  payload: {
    resourceType: string,
    // Shape of this field should follow API meta
    // See Example and /api/v1/Index/meta for details
    fields: object
  }
}
{
  command: "targetprocess:CreateResource",
  payload: {
    resourceType: "UserStory",
    fields: {
      // Reference fields like `Project` or `Feature`
      // should be specified as objects with `Id` field
      Project: { Id: 20 },
      Name: "New User Story",
      // You can also create nested objects
      Tasks: [
        { Name: "Task #1" },
        { Name: "Task #2" }
      ]
    }
  }
}

targetprocess:UpdateResource ermöglicht die Änderung der Felder einer bestehenden Targetprocess-Entität

{
  command: "targetprocess:UpdateResource",
  payload: {
    resourceType: string,
    resourceId: number,
    // Shape of this field should follow API meta
    // See Example and /api/v1/Index/meta for details
    fields: object
  }
}
{
  command: "targetprocess:UpdateResource",
  payload: {
    resourceType: "UserStory",
    resourceId: 20,
    fields: {
      // Reference fields like `Project` or `Feature`
      // should be specified as objects with `Id` field
      Feature: { Id: 30 },
      Name: "Updated User Story name"
    }
  }
}

targetprocess:DeleteResource ermöglicht das Löschen einer bestehenden Targetprocess-Entität

{
  command: "targetprocess:DeleteResource",
  payload: {
    resourceType: string,
    resourceId: number
  }
}
{
  command: "targetprocess:DeleteResource",
  payload: {
    resourceType: "UserStory",
    resourceId: 20
  }
}

targetprocess:MoveToState erlaubt es, Targetprocess-Entitäten wie Bugs oder User Storys in einen bestimmten Zustand zu versetzen - Initial, Planned oder Final.

{
  command: "targetprocess:MoveToState",
  payload: {
    resourceType: string,
    resourceId: number,
    stateKind: 'Initial' | 'Planned' | 'Final'
  }
}
{
  command: "targetprocess:MoveToState",
  payload: {
    resourceType: "UserStory",
    resourceId: 40,
    stateKind: 'Planned'
  }
}

Es ist auch möglich, den Zustand über den Namen des Zustands zu ändern.

return {
  command: "targetprocess:MoveToState",
  payload: {
    resourceType: "UserStory",
    resourceId: args.ResourceId,
    stateName: "In Testing"
  }
}

Formatierung der Daten

Um ein Datum auf der Grundlage einer bestimmten Zeitzone zu formatieren, kann die folgende Methode verwendet werden:

const myDate = new Date(); // 2020-02-10T11:16:34.240Z
const dateFormatter = new Intl.DateTimeFormat('en-US', { timeZone: "America/Chicago" });
const formattedDate = dateFormatter.format(myDate); // 2/10/2020

Wir raten von der Verwendung von .toLocaleDateString() ab, da der Speicher- und CPU-Verbrauch viel höher ist als bei der obigen Lösung.
Weitere Einzelheiten finden Sie in diesem Artikel.