-
Notifications
You must be signed in to change notification settings - Fork 21
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:
- You need more transactional control over a series of operations
- The end user does not have access to object/fields/operations you need to perform
- 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.
- 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;
}
}
- 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...
- We can call our endpoint by using
new Rest().request.post<SObject>
. - We can use
acc.prepareFor('apex');
to map ourAccount
object into the format that salesforce is expecting -
Account.fromSFObject(data)
to parse the response from salesforce back to ourAccount
object
If you'd prefer calling Invokable Methods ts-force makes that easy as well:
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;
}
}
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);