For now, just update the auth.username property to a connected sfdx-cli username.
Alternate authentication methods are supported. To see a full list of options, see
"ts-force-config" api section
Run Code Generation
$ npx ts-force-gen
After this completes, you should see that generated classes have been added to src/generated for the sObjects listed in our config.
Using ts-force
We will again use the sfdx-cli obtain a Salesforce access token. To do so from node, we'll need an additional dependency:
$ npm install @salesforce/core
In a production environment, you would likely obtain the access token via oAuth or other means. See the "Connecting with Salesforce" section for more details.
Create a new file src/index.ts and add the following code
src/index.ts
import { AuthInfo, Connection, Org } from '@salesforce/core';
import { Account, Contact } from './generated';
import { CompositeCollection, getStandardError, Rest } from 'ts-force';
// an async self invoking function (main)
(async () => {
// setup client
const { accessToken, instanceUrl } = await auth('sf-user@example.com'); // update username!
const restInstance = new Rest({
accessToken,
instanceUrl,
});
// create a new account
const acmeAccount = new Account({ name: 'acme', industry: 'manufacturing' }, restInstance);
await acmeAccount.insert();
console.log(acmeAccount.id);
// create 2 contacts
const collection = new CompositeCollection(restInstance);
await collection.insert([
new Contact({ accountId: acmeAccount.id, firstName: 'road', lastName: 'runner' }),
new Contact({ accountId: acmeAccount.id, firstName: 'wile', lastName: 'coyote' }),
]);
// run query contacts on "manufacturing" accounts
const contacts = await Contact.retrieve(
(f) => ({
select: [...f.select('id', 'name'), ...f.parent('account').select('id', 'name')],
where: [{ field: f.parent('account').select('industry'), val: 'manufacturing' }],
}),
{ restInstance },
);
console.log(contacts.length);
contacts.forEach((c) => console.log(c.name, c.account?.name));
// cleanup records
await acmeAccount.delete();
await collection.delete(contacts);
})().catch((e) => {
const stdErr = getStandardError(e);
console.error(JSON.stringify(stdErr.errorDetails));
});
/* helper function to get connection for SFDX-CLI */
async function auth(username: string) {
const authInfo = await AuthInfo.create({ username });
const connection = await Connection.create({ authInfo });
const org = await Org.create({ connection });
await org.refreshAuth();
return org.getConnection();
}
This code does the following:
Creates a Rest instance from via a sfdx-cli org connection
Inserts an Account
Inserts 2 Contacts related to the Account
Queries Contacts where Account.Industry = 'manufacturing'