Skip to content

The open alternative to Salesforce, designed for AI.

16.8 KB
Raw Blame
import { TEST_COMPANY_1_ID } from 'test/integration/constants/test-company-ids.constants';
import {
  TEST_PERSON_1_ID,
  TEST_PERSON_2_ID,
  TEST_PERSON_3_ID,
  TEST_PERSON_4_ID,
} from 'test/integration/constants/test-person-ids.constants';
import {
  TEST_PRIMARY_LINK_URL,
  TEST_PRIMARY_LINK_URL_AS_DOMAIN,
} from 'test/integration/constants/test-primary-link-url.constant';
import { makeRestApiRequest } from 'test/integration/rest/utils/make-rest-api-request.util';
import { deleteAllRecords } from 'test/integration/utils/delete-all-records';
import { generateRecordName } from 'test/integration/utils/generate-record-name';

describe('Core REST API Find Many endpoint', () => {
  const testPersonIds = [
    TEST_PERSON_1_ID,
    TEST_PERSON_2_ID,
    TEST_PERSON_3_ID,
    TEST_PERSON_4_ID,
  ];
  const testPersonJobTitles: Record<string, string> = {};

  beforeAll(async () => {
    await deleteAllRecords('person');
    await deleteAllRecords('company');

    await makeRestApiRequest({
      method: 'post',
      path: '/companies',
      body: {
        id: TEST_COMPANY_1_ID,
        domainName: {
          primaryLinkUrl: TEST_PRIMARY_LINK_URL,
        },
      },
    });

    let index = 0;

    for (const personId of testPersonIds) {
      const jobTitle = generateRecordName(personId);

      testPersonJobTitles[personId] = jobTitle;

      await makeRestApiRequest({
        method: 'post',
        path: '/people',
        body: {
          id: personId,
          jobTitle: jobTitle,
          position: index,
          companyId: TEST_COMPANY_1_ID,
        },
      });

      index++;
    }
  });

  it('should retrieve all people with pagination metadata', async () => {
    const response = await makeRestApiRequest({
      method: 'get',
      path: '/people',
    });

    expect(response.status).toBe(200);

    const people = response.body.data.people;
    const pageInfo = response.body.pageInfo;
    const totalCount = response.body.totalCount;

    expect(people).not.toBeNull();
    expect(Array.isArray(people)).toBe(true);
    expect(people.length).toBeGreaterThanOrEqual(testPersonIds.length);

    for (const personId of testPersonIds) {
      // @ts-expect-error legacy noImplicitAny
      const person = people.find((p) => p.id === personId);

      expect(person).toBeDefined();
      expect(person.jobTitle).toBe(testPersonJobTitles[personId]);
    }

    expect(pageInfo).toBeDefined();
    expect(pageInfo.startCursor).toBeDefined();
    expect(pageInfo.endCursor).toBeDefined();
    expect(typeof totalCount).toBe('number');
    expect(totalCount).toEqual(testPersonIds.length);
    expect(response.body.pageInfo.hasNextPage).toBe(false);
    expect(response.body.pageInfo.hasPreviousPage).toBe(false);
  });

  it('should limit results based on the limit parameter', async () => {
    const limit = testPersonIds.length - 1;
    const response = await makeRestApiRequest({
      method: 'get',
      path: `/people?limit=${limit}`,
    }).expect(200);

    const people = response.body.data.people;

    expect(people).not.toBeNull();
    expect(Array.isArray(people)).toBe(true);
    expect(people.length).toEqual(limit);
    expect(response.body.totalCount).toEqual(testPersonIds.length);
    expect(response.body.pageInfo.hasNextPage).toBe(true);
  });

  it('should return filtered totalCount', async () => {
    const response = await makeRestApiRequest({
      method: 'get',
      path: `/people?filter=position[lte]:1`,
    }).expect(200);

    const people = response.body.data.people;

    expect(people).not.toBeNull();
    expect(Array.isArray(people)).toBe(true);
    expect(people.length).toEqual(2);
    expect(response.body.totalCount).toEqual(2);
    expect(response.body.pageInfo.hasNextPage).toBe(false);
  });

  it('should filter results based on filter parameters', async () => {
    const response = await makeRestApiRequest({
      method: 'get',
      path: '/people?filter=position[lt]:2',
    }).expect(200);

    const filteredPeople = response.body.data.people;

    expect(filteredPeople).toBeDefined();
    expect(Array.isArray(filteredPeople)).toBe(true);
    expect(filteredPeople.length).toBe(2);
  });

  it('should support cursor-based pagination with starting_after', async () => {
    const initialResponse = await makeRestApiRequest({
      method: 'get',
      path: '/people?limit=2',
    }).expect(200);

    const people = initialResponse.body.data.people;
    const startCursor = initialResponse.body.pageInfo.startCursor;

    expect(people).toBeDefined();
    expect(people.length).toBe(2);
    expect(startCursor).toBeDefined();

    const nextPageResponse = await makeRestApiRequest({
      method: 'get',
      path: `/people?starting_after=${startCursor}&limit=1`,
    }).expect(200);

    const nextPagePeople = nextPageResponse.body.data.people;

    expect(nextPagePeople).toBeDefined();
    expect(nextPagePeople.length).toBe(1);
    expect(nextPagePeople[0].id).toBe(people[1].id);
    expect(nextPageResponse.body.pageInfo.hasPreviousPage).toBe(true);
  });

  it('should support cursor-based pagination with ending_before', async () => {
    const initialResponse = await makeRestApiRequest({
      method: 'get',
      path: '/people?limit=4',
    }).expect(200);

    const people = initialResponse.body.data.people;
    const endCursor = initialResponse.body.pageInfo.endCursor;

    expect(people).toBeDefined();
    expect(people.length).toBe(4);
    expect(endCursor).toBeDefined();

    const nextPageResponse = await makeRestApiRequest({
      method: 'get',
      path: `/people?ending_before=${endCursor}&limit=2`,
    }).expect(200);

    const nextPagePeople = nextPageResponse.body.data.people;

    expect(nextPagePeople).toBeDefined();
    expect(nextPagePeople.length).toBe(2);
    expect(nextPagePeople[0].id).toBe(people[1].id);
    expect(nextPagePeople[1].id).toBe(people[2].id);
    expect(nextPageResponse.body.pageInfo.hasNextPage).toBe(true);
  });

  it('should support ordering Asc of results', async () => {
    const ascResponse = await makeRestApiRequest({
      method: 'get',
      path: '/people?order_by=position[AscNullsLast]',
    }).expect(200);

    const ascPeople = ascResponse.body.data.people;

    expect(ascPeople).toEqual(
      [...ascPeople].sort((a, b) => a.position - b.position),
    );
  });

  it('should support filtering on a relation field id', async () => {
    const response = await makeRestApiRequest({
      method: 'get',
      path: `/people?filter=companyId[in]:["${TEST_COMPANY_1_ID}"]`,
    }).expect(200);

    const filteredPeople = response.body.data.people;

    expect(filteredPeople.length).toBeGreaterThan(0);
  });

  it('should support ordering Desc of results', async () => {
    const descResponse = await makeRestApiRequest({
      method: 'get',
      path: '/people?order_by=position[DescNullsLast]',
    }).expect(200);

    const descPeople = descResponse.body.data.people;

    expect(descPeople).toEqual(
      [...descPeople].sort((a, b) => -(a.position - b.position)),
    );
  });

  it('should support pagination with ordering', async () => {
    const descResponse = await makeRestApiRequest({
      method: 'get',
      path: '/people?order_by=position[DescNullsLast]&limit=2',
    }).expect(200);

    const descPeople = descResponse.body.data.people;
    const endingBefore = descResponse.body.pageInfo.endCursor;
    const lastPosition = descPeople[descPeople.length - 1].position;

    expect(descResponse.body.pageInfo.hasNextPage).toBe(true);
    expect(descPeople.length).toEqual(2);
    expect(lastPosition).toEqual(2);

    const descResponseWithPaginationResponse = await makeRestApiRequest({
      method: 'get',
      path: `/people?order_by=position[DescNullsLast]&limit=2&starting_after=${endingBefore}`,
    }).expect(200);

    const descResponseWithPagination =
      descResponseWithPaginationResponse.body.data.people;

    expect(descResponseWithPagination.length).toEqual(2);
    expect(descResponseWithPagination[0].position).toEqual(lastPosition - 1);
  });

  it('should handle invalid cursor gracefully', async () => {
    const response = await makeRestApiRequest({
      method: 'get',
      path: '/people?starting_after=invalid-cursor',
    });

    expect(response.body.error).toBe('BadRequestException');
    expect(response.body.messages[0]).toContain('Invalid cursor');
  });

  it('should combine filtering, ordering, and pagination', async () => {
    const response = await makeRestApiRequest({
      method: 'get',
      path: '/people?filter=position[gt]:0&order_by=jobTitle[AscNullsFirst]&limit=2',
    }).expect(200);

    const people = response.body.data.people;

    const pageInfo = response.body.pageInfo;

    expect(people).toBeDefined();
    expect(people.length).toBeLessThanOrEqual(2);
    expect(pageInfo).toBeDefined();

    expect(people).toEqual(
      [...people].sort((a, b) => a.jobTitle.localeCompare(b.jobTitle)),
    );
  });

  it('should should throw an error when trying to order by a composite field', async () => {
    await makeRestApiRequest({
      method: 'get',
      path: '/people?order_by=name[AscNullsLast]',
    }).expect(400);
  });

  it('should support depth 0 parameter', async () => {
    const response = await makeRestApiRequest({
      method: 'get',
      path: '/people?depth=0',
    }).expect(200);

    const people = response.body.data.people;

    expect(people).toBeDefined();

    const person = people[0];

    expect(person).toBeDefined();
    expect(person.companyId).toBeDefined();
    expect(person.company).not.toBeDefined();
  });

  it('should support depth 1 parameter', async () => {
    const response = await makeRestApiRequest({
      method: 'get',
      path: '/people?depth=1',
    }).expect(200);

    const people = response.body.data.people;

    const person = people[0];

    expect(person.company).toBeDefined();
    expect(person.company.domainName.primaryLinkUrl).toBe(
      TEST_PRIMARY_LINK_URL_AS_DOMAIN,
    );

    expect(person.company.people).not.toBeDefined();
  });

  it('should not support depth 2 parameter', async () => {
    await makeRestApiRequest({
      method: 'get',
      path: '/people?depth=2',
    }).expect(400);
  });

  describe('cursor pagination ordered by a relation field', () => {
    it('should continue past the first page when depth loads the ordered relation', async () => {
      const ids: string[] = [];
      let startingAfter: string | undefined = undefined;

      for (let iteration = 0; iteration < 10; iteration++) {
        const path: string =
          '/people?order_by=company.name[AscNullsLast]&limit=2&depth=1' +
          (startingAfter ? `&starting_after=${startingAfter}` : '');
        const response = await makeRestApiRequest({
          method: 'get',
          path,
        }).expect(200);

        ids.push(
          ...response.body.data.people.map(
            (person: { id: string }) => person.id,
          ),
        );

        if (!response.body.pageInfo.hasNextPage) {
          break;
        }

        startingAfter = response.body.pageInfo.endCursor;
      }

      expect(ids).toHaveLength(testPersonIds.length);
      expect(new Set(ids).size).toBe(testPersonIds.length);
    });

    // Regression for #24333: continuation must not require any depth.
    it('should continue past the first page at depth 0', async () => {
      const ids: string[] = [];
      let startingAfter: string | undefined = undefined;

      for (let iteration = 0; iteration < 10; iteration++) {
        const path: string =
          '/people?order_by=company.name[AscNullsLast]&limit=2&depth=0' +
          (startingAfter ? `&starting_after=${startingAfter}` : '');
        const response = await makeRestApiRequest({
          method: 'get',
          path,
        }).expect(200);

        ids.push(
          ...response.body.data.people.map(
            (person: { id: string }) => person.id,
          ),
        );

        if (!response.body.pageInfo.hasNextPage) {
          break;
        }

        startingAfter = response.body.pageInfo.endCursor;
      }

      expect(ids).toHaveLength(testPersonIds.length);
      expect(new Set(ids).size).toBe(testPersonIds.length);
    });
  });

  describe('cursor pagination ordered by a nullable field', () => {
    const datedOpportunityCloseDates = [
      '2026-03-01T00:00:00.000Z',
      '2026-03-02T00:00:00.000Z',
      '2026-03-03T00:00:00.000Z',
    ];
    const opportunityCount = datedOpportunityCloseDates.length + 2;

    beforeAll(async () => {
      await deleteAllRecords('opportunity');

      for (const [index, closeDate] of datedOpportunityCloseDates.entries()) {
        await makeRestApiRequest({
          method: 'post',
          path: '/opportunities',
          body: { name: `REST dated opportunity ${index + 1}`, closeDate },
        });
      }

      for (const index of [1, 2]) {
        await makeRestApiRequest({
          method: 'post',
          path: '/opportunities',
          body: { name: `REST undated opportunity ${index}` },
        });
      }
    });

    afterAll(async () => {
      await deleteAllRecords('opportunity');
    });

    it('should return every record when paginating with starting_after', async () => {
      const ids: string[] = [];
      let startingAfter: string | undefined = undefined;

      for (let iteration = 0; iteration < 10; iteration++) {
        const path: string =
          '/opportunities?order_by=closeDate[AscNullsLast]&limit=2' +
          (startingAfter ? `&starting_after=${startingAfter}` : '');
        const response = await makeRestApiRequest({
          method: 'get',
          path,
        }).expect(200);

        ids.push(
          ...response.body.data.opportunities.map(
            (opportunity: { id: string }) => opportunity.id,
          ),
        );

        if (!response.body.pageInfo.hasNextPage) {
          break;
        }

        startingAfter = response.body.pageInfo.endCursor;
      }

      expect(ids).toHaveLength(opportunityCount);
      expect(new Set(ids).size).toBe(opportunityCount);
    });
  });

  describe('fields parameter', () => {
    it('should only return the requested fields and id', async () => {
      const response = await makeRestApiRequest({
        method: 'get',
        path: '/people?fields=jobTitle,emails',
      }).expect(200);

      const people = response.body.data.people;

      expect(people.length).toBe(testPersonIds.length);

      for (const person of people) {
        expect(Object.keys(person).sort()).toEqual(
          ['emails', 'id', 'jobTitle'].sort(),
        );
        expect(person.emails).toHaveProperty('primaryEmail');
      }
    });

    it('should paginate on a field that is not requested', async () => {
      const fullOrderResponse = await makeRestApiRequest({
        method: 'get',
        path: '/people?order_by=position[AscNullsFirst]&limit=4',
      }).expect(200);

      const expectedIds = fullOrderResponse.body.data.people.map(
        (person: { id: string }) => person.id,
      );

      const firstPageResponse = await makeRestApiRequest({
        method: 'get',
        path: '/people?fields=jobTitle&order_by=position[AscNullsFirst]&limit=2',
      }).expect(200);

      const firstPage = firstPageResponse.body.data.people;

      expect(firstPage[0].position).toBeUndefined();
      expect(firstPageResponse.body.pageInfo.hasNextPage).toBe(true);

      const secondPageResponse = await makeRestApiRequest({
        method: 'get',
        path: `/people?fields=jobTitle&order_by=position[AscNullsFirst]&limit=2&starting_after=${firstPageResponse.body.pageInfo.endCursor}`,
      }).expect(200);

      const paginatedIds = [
        ...firstPage,
        ...secondPageResponse.body.data.people,
      ].map((person: { id: string }) => person.id);

      expect(paginatedIds).toEqual(expectedIds);
    });

    it('should only expand requested relations at depth 1', async () => {
      const withoutRelationResponse = await makeRestApiRequest({
        method: 'get',
        path: '/people?fields=jobTitle&depth=1',
      }).expect(200);

      expect(
        withoutRelationResponse.body.data.people[0].company,
      ).toBeUndefined();

      const withRelationResponse = await makeRestApiRequest({
        method: 'get',
        path: '/people?fields=jobTitle,company&depth=1',
      }).expect(200);

      const person = withRelationResponse.body.data.people[0];

      expect(person.company.id).toBe(TEST_COMPANY_1_ID);
      expect(person.pointOfContactForOpportunities).toBeUndefined();
    });

    it('should return 400 on unknown fields', async () => {
      await makeRestApiRequest({
        method: 'get',
        path: '/people?fields=jobTitle,unknownField',
      })
        .expect(400)
        .expect((res) => {
          expect(res.body.error).toBe('BadRequestException');
          expect(res.body.messages[0]).toContain('unknownField');
        });
    });

    it('should return 400 on an empty fields parameter', async () => {
      await makeRestApiRequest({
        method: 'get',
        path: '/people?fields=',
      }).expect(400);
    });
  });
});