JavaScript Referencia

Variables de script para el origen de entidad modificado

args.Author — un objeto que representa el modificador

args.Current — este es un objeto que representa el estado actual de la entidad modificada.

// 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 — una cadena que representa el último tipo de modificación. Los valores disponibles son: «Creado», «Actualizado», «Eliminado» args.Previous — un objeto que representa el estado de la entidad antes de la modificación. Cuando args.Modification es "Created", este campo se establece en null
const originalEffort = args.Previous.Effort;
args.ResourceId — un número que contiene el ID de la entidad args.ResourceType modificada — una cadena que representa el tipo de entidad modificada, por ejemplo, "UserStory", «Bug», "TeamAssignment". args.ChangedFields — una matriz de cadenas que contiene el nombre de los campos que se modificaron en el ámbito del evento que activó la regla.
// Check whether the name of the User Story was modified:
const wasNameChanged = args.ChangedFields.contains("Name");

Variables de script para la fuente de webhook entrante

args.headers — un objeto que representa el encabezado de la solicitud http entrante. args.body — un objeto que representa el cuerpo de la solicitud http entrante.
const branch = args.body.object_attributes.ref;

Consultar la API de Targetprocess

context.getService("targetprocess/apiv2") — Una llamada a esta función devuelve un servicio que permite al script realizar consultas a la API de v2 Targetprocess. require("targetprocess/api/v2") — El servicio también se puede recuperar de esta manera. Aquí hay un ejemplo de cómo recuperar 100 errores ordenados por nombre para una historia de usuario modificada:
const userStoryId = args.ResourceId;

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

// ___PROTECTED_16___ here mirrors the shape of API v2 query parameters,
// such as ___PROTECTED_17___, ___PROTECTED_18___, ___PROTECTED_19___, 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"
};

// ___PROTECTED_20___ 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, ___PROTECTED_21___ is an array of objects with the fields specified in ___PROTECTED_22___, e.g.
// [ 
//   {id: 1, name: "First Bug"},
//   {id: 2, name: "Second Bug"}
// ]

const firstBugName = bugs[0].name;
El cliente de la API de Targetprocess también puede consultar recursos individuales utilizando getByIdAsync el método
const api = context.getService("targetprocess/api/v2");
const userStoryDetails = await api.getByIdAsync(
  // Return details of UserStory#42
  "UserStory", 42,
  // 3rd parameter acts like ___PROTECTED_24___ 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);
}

Solicitudes HTTP de ejecución

context.getService("http") - Una llamada a esta función devuelve un servicio que permite al script realizar HTTP solicitudes a API externas. require("http") — El servicio también se puede recuperar de esta manera. HTTP El servicio admite los siguientes métodos:
  • http.getAsync()
  • http.postAsync()
  • http.sendAsync()
  • http.putAsync()
  • http.deleteAsync()
  • http.patchAsync()

Aquí hay un ejemplo que obtiene datos de una API de terceros.

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);
Otro ejemplo con la consulta posterior a algún 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"
  }
});
Ejemplo del método PUT.
const http = context.getService("http")
 
const res = await http.putAsync("http://dummy.restapiexample.com/api/v1/update/21");
Método DELETE.
const http = require('http');

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

Acceso a los HTTP encabezados de respuesta

Algunas integraciones pasan la información requerida en HTTP los encabezados. Actualmente, existe una forma de acceder a ellos desde las reglas de automatización de JS. sendAsync Se ha añadido el método al http servicio. Este método devuelve un result objeto que proporciona acceso a los componentes internos de la respuesta, e. ejemplo, statusCode, encabezados.
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
Nota: Lista blanca para solicitudes de reglas de automatización Si necesita permitir consultas del servicio de reglas de automatización en su proxy\\firewall, la lista de direcciones IP que se deben incluir en la lista blanca se encuentra en Rango de direcciones IP públicasApptio de Targetprocess de la comunidad.

Comandos de acción

Esta sección describe el formato de los comandos que pueden devolverse desde los bloques JavaScript de acción. El formato del comando se describe con TypeScript la sintaxis, y la pestaña Ejemplo muestra ejemplos de comandos que funcionan. targetprocess:CreateResource permite crear una nueva entidad Targetprocess, como una tarea o un proyecto.
{
  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 ___PROTECTED_37___ or ___PROTECTED_38___
      // should be specified as objects with ___PROTECTED_39___ field
      Project: { Id: 20 },
      Name: "New User Story",
      // You can also create nested objects
      Tasks: [
        { Name: "Task #1" },
        { Name: "Task #2" }
      ]
    }
  }
}
targetprocess:UpdateResource permite modificar los campos de la entidad Targetprocess existente
{
  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 ___PROTECTED_41___ or ___PROTECTED_42___
      // should be specified as objects with ___PROTECTED_43___ field
      Feature: { Id: 30 },
      Name: "Updated User Story name"
    }
  }
}
targetprocess:DeleteResource permite eliminar la entidad Targetprocess existente
{
  command: "targetprocess:DeleteResource",
  payload: {
    resourceType: string,
    resourceId: number
  }
}
{
  command: "targetprocess:DeleteResource",
  payload: {
    resourceType: "UserStory",
    resourceId: 20
  }
}
targetprocess:MoveToState Permite mover una entidad de Targetprocess, como un error o una historia de usuario, al estado especificado: inicial, planificado o final.
{
  command: "targetprocess:MoveToState",
  payload: {
    resourceType: string,
    resourceId: number,
    stateKind: 'Initial' | 'Planned' | 'Final'
  }
}
{
  command: "targetprocess:MoveToState",
  payload: {
    resourceType: "UserStory",
    resourceId: 40,
    stateKind: 'Planned'
  }
}
También es posible cambiar el estado por el nombre del estado.
return {
  command: "targetprocess:MoveToState",
  payload: {
    resourceType: "UserStory",
    resourceId: args.ResourceId,
    stateName: "In Testing"
  }
}

Formato de fechas

Para dar formato a una fecha basándose en una zona horaria específica, se puede utilizar el siguiente método:
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
No recomendamos su uso .toLocaleDateString() porque el consumo de memoria y CPU es mucho mayor que con la solución anterior. Para más detalles, consulta este artículo.