Extraits de code
Trois extraits commentés. Les deux premiers viennent du code de ce portfolio, en production. Le troisième est un exemple illustratif : il reprend un principe que j'ai développé en mission, réécrit pour ne contenir aucun code de client.
ApexCode de ce portfolio
Trigger et service : envoyer sans jamais bloquer l'enregistrement
Ce qu'il faut regarder
- Le trigger ne contient aucune logique : il délègue à une classe de service testable.
- Tous les e-mails partent en un seul appel, quel que soit le nombre de Leads insérés.
- Un échec d'envoi ne lève pas d'exception : il devient une tâche visible sur le Lead.
trigger PortfolioLeadTrigger on Lead (after insert) { PortfolioLeadEmailService.notify(Trigger.new);} public with sharing class PortfolioLeadEmailService { public static void notify(List<Lead> leads) { List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>(); List<Id> leadIds = new List<Id>(); List<String> kinds = new List<String>(); for (Lead l : leads) { if (l.LeadSource != PORTFOLIO_SOURCE) { continue; // only leads created by the website } if (String.isNotBlank(l.Email)) { mails.add(buildConfirmation(l)); leadIds.add(l.Id); kinds.add('Confirmation'); } mails.add(buildOwnerAlert(l)); leadIds.add(l.Id); kinds.add('Notification'); } if (mails.isEmpty()) { return; } List<Task> failures = new List<Task>(); try { // One call for the whole batch; allOrNone = false keeps the good ones List<Messaging.SendEmailResult> results = Messaging.sendEmail(mails, false); for (Integer i = 0; i < results.size(); i++) { if (!results[i].isSuccess()) { failures.add(failureTask(leadIds[i], kinds[i], String.valueOf(results[i].getErrors()))); } } } catch (Exception e) { // e.g. deliverability switched off: the Lead must still be saved for (Integer i = 0; i < leadIds.size(); i++) { failures.add(failureTask(leadIds[i], kinds[i], e.getMessage())); } } if (!failures.isEmpty()) { Database.insert(failures, false); } }}TypeScriptCode de ce portfolio
Flux OAuth 2.0 JWT Bearer côté serveur
Ce qu'il faut regarder
- La clé privée est lue dans une variable d'environnement et ne sort jamais du serveur.
- Le JWT expire au bout de trois minutes : il ne sert qu'à obtenir le jeton d'accès.
- La connexion est mise en cache pour ne pas redemander un jeton à chaque requête.
async function fetchAccessToken() { const pem = process.env.SF_PRIVATE_KEY!.replace(/\\n/g, "\n"); const key = await importPKCS8(pem, "RS256"); const now = Math.floor(Date.now() / 1000); // Signed assertion: who is asking (client id), for whom (username), where (login URL) const jwt = await new SignJWT({}) .setProtectedHeader({ alg: "RS256" }) .setIssuer(process.env.SF_CLIENT_ID!) .setSubject(process.env.SF_USERNAME!) .setAudience(process.env.SF_LOGIN_URL!) .setExpirationTime(now + 3 * 60) .sign(key); const res = await fetch(`${process.env.SF_LOGIN_URL}/services/oauth2/token`, { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer", assertion: jwt, }).toString(), }); if (!res.ok) { throw new Error(`Salesforce token exchange failed: ${res.status}`); } const data = await res.json(); return { accessToken: data.access_token, instanceUrl: data.instance_url };} export async function getSalesforceConnection() { if (cachedConn && Date.now() - cachedAt < TTL_MS) return cachedConn; // reuse for one hour const { accessToken, instanceUrl } = await fetchAccessToken(); cachedConn = new jsforce.Connection({ instanceUrl, accessToken }); cachedAt = Date.now(); return cachedConn;}LWCExemple illustratif
Action rapide « Démarrer l'intervention » avec géolocalisation
Ce qu'il faut regarder
- La position vient du navigateur de l'appareil ; l'utilisateur doit l'autoriser.
- La conversion des coordonnées en adresse se fait côté serveur, dans la méthode Apex.
- Chaque issue est gérée : succès, refus de localisation, erreur du serveur.
import { LightningElement, api } from 'lwc';import { ShowToastEvent } from 'lightning/platformShowToastEvent';import { CloseActionScreenEvent } from 'lightning/actions';import startIntervention from '@salesforce/apex/InterventionController.startIntervention'; export default class StartIntervention extends LightningElement { @api recordId; // the service appointment the action was launched from isLoading = false; handleStart() { this.isLoading = true; navigator.geolocation.getCurrentPosition( (position) => this.save(position.coords), () => this.finish('error', 'Position indisponible : autorisez la localisation.'), { enableHighAccuracy: true, timeout: 10000 } ); } async save({ latitude, longitude }) { try { // Apex stores the coordinates, resolves the address and sets the status const address = await startIntervention({ appointmentId: this.recordId, latitude, longitude }); this.finish('success', address); this.dispatchEvent(new CloseActionScreenEvent()); } catch (error) { this.finish('error', error?.body?.message ?? 'Erreur inconnue'); } } finish(variant, message) { this.isLoading = false; this.dispatchEvent(new ShowToastEvent({ title: 'Intervention', message, variant })); }}