Skip to content

Custom Endpoints

Charlie Jonas edited this page May 23, 2019 · 6 revisions

Unfortunately, there are instances where the standard rest API may not meet all your needs. This typically happens if:

  1. You need more transactional control over a series of operations
  2. The end user does not have access to object/fields/operations you need to perform
  3. This is a public endpoint and you need to enforce logic on the service side

However, we can call these custom endpoints using ts-force and often even use our generated classes with the request and response.

@RestResource

  1. Login to your org and add a new apex class called RestServiceTesting :
@RestResource(urlMapping='/myservice')
global with sharing class RestServiceTesting {
    @HttpPost
     global static Account doPost(Account acc) {
        return acc;
    }
}
  1. Add the following code to your ts-force project
let acc = new Account({
    id: '123',
    contacts: [new Contact({
        firstName: 'john',
        lastName: 'doe'
    })],
    owner: new User({
        'email': 'example@gmai.com'
    })
});

const sfSob = acc.prepareFor('apex');
let data = (await new Rest().request.post<SObject>(
    '/services/apexrest/myservice',
    { acc: sfSob }
)).data;
const retAcc = Account.fromSFObject(data);
console.log(retAcc.id, retAcc.contacts.length);

Notice how...

  1. We can call our endpoint by using new Rest().request.post<SObject>.
  2. We can use acc.prepareFor('apex'); to map our Account object into the format that salesforce is expecting
  3. Account.fromSFObject(data) to parse the response from salesforce back to our Account object

Invokable

If you'd prefer calling Invokable Methods ts-force makes that easy as well:

Apex

public class AccountInsertAction {
  @InvocableMethod(label='Insert Accounts' description='Inserts the accounts specified and returns the IDs of the new accounts.')
  public static List<ID> insertAccounts(List<Account> accounts) {
    Database.SaveResult[] results = Database.insert(accounts);
    List<ID> accountIds = new List<ID>();
    for (Database.SaveResult result : results) {
      if (result.isSuccess()) {
        accountIds.add(result.getId());
      }
    }
    return accountIds;
  }
}

calling from ts-force

let acc1 = new Account({
    name: 'acme',
    annualRevenue: 10
});

let acc2 = new Account({
    name: 'stark',
    annualRevenue: 10000
});


//prepare data for invokable
const data = [
   { accounts: acc1.prepareFor('apex') },
   { accounts: acc2.prepareFor('apex') }
];

let results = await rest.invokeAction<SObject>('AccountInsertAction', data);

// map list of results be to ts-force RestObjects
const returnedAccounts = results.map(rData => Account.fromSFObject(rData.outputValues.output));

console.log(returnedAccounts[0].id);