Skip to content

Commit

Permalink
Stop replacing consecutive spaces (#5)
Browse files Browse the repository at this point in the history
Add example script for data transfer
  • Loading branch information
surajp authored Jun 21, 2020
1 parent e06f9a9 commit 35e1471
Show file tree
Hide file tree
Showing 5 changed files with 138 additions and 21 deletions.
11 changes: 10 additions & 1 deletion force-app/main/default/classes/APICallController.cls
Original file line number Diff line number Diff line change
@@ -1,8 +1,17 @@
/**
** description: Controller for making api calls and sending the response back
* description: Controller for making api calls and sending the response back
**/

public with sharing class APICallController {
/**
* description Given an endpoint, request params and headers, callout the api and return the response
* @param endpoint The endpoint to callout to
* @param method The http method to use
* @param bodyStr The request body string.
* @param headers Map of string key and value for request headers
* @return HttpResponseWrapper
*
*/
@AuraEnabled
public static HttpResponseWrapper makeApiCall(
String endPoint,
Expand Down
44 changes: 29 additions & 15 deletions force-app/main/default/classes/DynamicSOQLDMLController.cls
Original file line number Diff line number Diff line change
@@ -1,38 +1,52 @@
public with sharing class DynamicSOQLDMLController {
/**
* Execute a Soql Query
* @param query The soql query to execute
*
* @return SObject[]
**/
@AuraEnabled
public static SObject[] executeSoqlQuery(String query) {
return Database.query(query);
}

/**
* Get JavaScript from a Custom Metadata with a given name
* @param cmdtName The name of Custom Metadata record to fetch the script from
*
* @return String
**/
@AuraEnabled(cacheable=true)
public static String getJSFromCmdt(String cmdtName) {
JS_Button__mdt[] jsButton = [
SELECT Script__c
FROM JS_Button__mdt
WHERE DeveloperName = :cmdtName
LIMIT 1
];
JS_Button__mdt[] jsButton = [SELECT Script__c FROM JS_Button__mdt WHERE DeveloperName = :cmdtName LIMIT 1];
if (jsButton.size() == 1)
return jsButton[0].Script__c;
else
return '';
}

/**
* Short Description
* @param recordId Get the SObject Type given a record Id
*
* @return String
**/
@AuraEnabled(cacheable=true)
public static String getSObjectTypeFromId(Id recordId) {
return recordId.getSObjectType().getDescribe().getName();
}

/**
* Execute a DML statement
* @param operation 'Insert','Update' or 'Upsert'
* @param strdata The records to update, stringified
* @param sobjectType The SObject type to perform the DML on
*
* @return Id[]
**/
@AuraEnabled
public static Id[] executeDml(
String operation,
String strData,
String sObjectType
) {
SObject[] records = (SObject[]) JSON.deserialize(
strData,
Type.forName('List<' + sObjectType + '>')
);
public static Id[] executeDml(String operation, String strData, String sObjectType) {
SObject[] records = (SObject[]) JSON.deserialize(strData, Type.forName('List<' + sObjectType + '>'));
if (operation == 'insert') {
insert records;
return new List<Id>(new Map<Id, SObject>(records).keySet());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
<field>Script__c</field>
<value xsi:type="xsd:string">let acct = || Select NumberOfEmployees from Account where Id=&apos;${recordId}&apos; ||;


acct[0].NumberOfEmployees = (acct[0].NumberOfEmployees || 0) + 10;

let acctId = || update acct ||;
Expand Down
10 changes: 6 additions & 4 deletions force-app/main/default/lwc/jsButtonLwc/jsButtonLwc.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ import getSObjectType from "@salesforce/apex/DynamicSOQLDMLController.getSObject
import { ShowToastEvent } from "lightning/platformShowToastEvent";
import HttpRequest from "c/httpRequest";

const REGEX_SOQL = "\\|\\|\\s?(select\\s+[^|]+)\\s?\\|\\|";
const REGEX_UPDATE = "\\|\\|\\s?update\\s([^|;]+);?\\s*\\|\\|";
const REGEX_SOQL = "\\|\\|\\s+(select\\s+[^|]+)\\s+\\|\\|";
const REGEX_UPDATE = "\\|\\|\\s+update\\s+([\\w\\d_]+).*\\|\\|";
const REGEX_INSERT_UPSERT =
"\\|\\|\\s?(insert|upsert)\\s([\\w\\d_]+)\\s?\\(\\s?(\\w+).*\\|\\|";
"\\|\\|\\s*(insert|upsert)\\s+([\\w\\d_]+)\\s*\\(\\s*(\\w+).*\\|\\|";

export default class JsButtonLwc extends LightningElement {
@api js;
Expand Down Expand Up @@ -77,7 +77,8 @@ export default class JsButtonLwc extends LightningElement {

async runJS(js) {
//replace consecutive spaces
js = js.replace(/\s+/g, " ");
//don't replace consecutive spaces
//js = js.replace(/\s+/g, " ");

//parse soql
js = js.replace(
Expand All @@ -96,6 +97,7 @@ export default class JsButtonLwc extends LightningElement {
new RegExp(REGEX_INSERT_UPSERT, "gi"),
"await this.executeDml('$1',$3,'$2');"
);
//eslint-disable-next-line
let op = await Function("recordId", `return (async ()=>{${js}})()`).bind(
this
)(this.recordId);
Expand Down
93 changes: 93 additions & 0 deletions scripts/jsButton/copyData.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
/***
* This script moves Account, Contact and Opportunity data from a source instance to the current SF instance.
* The source instance is expected to be configured using a named credential named 'source'
*/
let baseurl = "callout:source/services/data/v48.0/query?q=";
this.httpRequest.setEndpoint(baseurl + "Select+Id,Name+from+Account");
this.httpRequest.addHeader("Accept", "application/json");
let resp = await this.httpRequest.send();
resp = JSON.parse(resp.body);

if (!resp.done) {
alert("Request to fetch Accounts failed");
}
let accts = resp.records;
this.httpRequest.setEndpoint(
baseurl + "Select+Id,LastName,FirstName,Email,AccountId+from+Contact"
);
resp = await this.httpRequest.send();
resp = JSON.parse(resp.body);
if (!resp.done) {
alert("Request to fetch Contacts failed");
}
let contacts = resp.records;

this.httpRequest.setEndpoint(
baseurl +
"Select+Id,Name,CloseDate,StageName,AccountId,ContactId+from+Opportunity"
);
resp = await this.httpRequest.send();
resp = JSON.parse(resp.body);
if (!resp.done) {
alert("Request to fetch Opportunities failed");
}
let opps = resp.records;

let acctsToInsert = accts.map((a) => {
let b = { ...a };
delete b.Id;
delete b.attributes;
return b;
});

let newAcctIds=[];
try{
newAcctIds = || insert Account(acctsToInsert) ||;
}catch(err){
alert(JSON.stringify(err));
}
let acctIdMap = accts.reduce(
(obj, a, i) => ({ ...obj, [a.Id]: newAcctIds[i] }),
{}
);

let contactsToInsert = contacts
.map((c) => {
let d = { ...c, AccountId: acctIdMap[c.AccountId] };
delete d.Id;
delete d.attributes;
return d;
})
.filter((c) => c.AccountId);

let newCtctIds = [];
try {
newCtctIds = || insert Contact(contactsToInsert) ||;
} catch (err) {
alert(JSON.stringify(err));
}
let ctctIdMap = contacts.reduce(
(obj, c, i) => ({ ...obj, [c.Id]: newCtctIds[i] }),
{}
);

let oppsToInsert = opps
.map((o) => {
let p = {
...o,
AccountId: acctIdMap[o.AccountId],
ContactId: ctctIdMap[o.ContactId]
};
delete p.Id;
delete p.attributes;
return p;
})
.filter((o) => o.AccountId);

let newOppIds = [];
try {
newOppIds = || insert Opportunity(oppsToInsert) ||;
} catch (err) {
alert(JSON.stringify(err));
}
alert('Data transfer complete');

0 comments on commit 35e1471

Please sign in to comment.