From 875df78c515d7978b5b06cb6eaebbd823b8fb7b7 Mon Sep 17 00:00:00 2001 From: Pomu Date: Thu, 11 Dec 2014 10:36:00 +0900 Subject: [PATCH 01/24] Fix typo in comment, code formatting, return type consistency --- forcetk.js | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/forcetk.js b/forcetk.js index 3b94914..55d00b4 100644 --- a/forcetk.js +++ b/forcetk.js @@ -117,7 +117,7 @@ if (forcetk.Client === undefined) { * Set a session token and the associated metadata in the client. * @param sessionId a salesforce.com session ID. In a Visualforce page, * use '{!$Api.sessionId}' to obtain a session ID. - * @param [apiVersion="21.0"] Force.com API version + * @param [apiVersion="27.0"] Force.com API version * @param [instanceUrl] Omit this if running on Visualforce; otherwise * use the value from the OAuth token. */ @@ -200,9 +200,9 @@ if (forcetk.Client === undefined) { * @param mimetype of the file * @param callback function to which response will be passed * @param [error=null] function to which request will be passed in case of error - * @param rety true if we've already tried refresh token flow once - **/ - forcetk.Client.prototype.getChatterFile = function(path,mimeType,callback,error,retry) { + * @param retry true if we've already tried refresh token flow once + */ + forcetk.Client.prototype.getChatterFile = function(path, mimeType, callback, error, retry) { var that = this; var url = this.instanceUrl + path; @@ -258,8 +258,8 @@ if (forcetk.Client === undefined) { * @param [error=null] function to which jqXHR will be passed in case of error * @param [method="GET"] HTTP method for call * @param [payload=null] payload for POST/PATCH etc - * @param [paramMap={}] parameters to send as header values for POST/PATCH etc - * @param [retry] specifies whether to retry on error + * @param [paramMap={}] parameters to send as header values for POST/PATCH etc + * @param [retry] specifies whether to retry on error */ forcetk.Client.prototype.apexrest = function(path, callback, error, method, payload, paramMap, retry) { var that = this; @@ -388,7 +388,7 @@ if (forcetk.Client === undefined) { fieldlist = null; } var fields = fieldlist ? '?fields=' + fieldlist : ''; - this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' + id + return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' + id + fields, callback, error); } @@ -484,4 +484,4 @@ if (forcetk.Client === undefined) { return this.ajax('/' + this.apiVersion + '/search?q=' + escape(sosl) , callback, error); } -} \ No newline at end of file +} From 3ceda4cdfa2f3816bf07d05a382eeefcaaa57932 Mon Sep 17 00:00:00 2001 From: Pat Patterson Date: Thu, 11 Dec 2014 12:26:10 -0800 Subject: [PATCH 02/24] Remove RemoteTK, don't use proxy with REST API in Visualforce, add createBlob, updateBlob --- README.markdown | 95 +++++------ RemoteTK.component | 201 ----------------------- RemoteTKController.cls | 315 ------------------------------------- RemoteTKExample.page | 150 ------------------ RemoteTKMobile.page | 144 ----------------- TestRemoteTKController.cls | 306 ----------------------------------- app.js | 62 ++++---- example.html | 16 +- example.page | 9 +- forcetk.js | 186 +++++++++++++++++----- mobile.html | 16 +- mobile.page | 9 +- mobileapp.js | 82 +++++----- phonegap.html | 22 +-- 14 files changed, 299 insertions(+), 1314 deletions(-) delete mode 100644 RemoteTK.component delete mode 100644 RemoteTKController.cls delete mode 100644 RemoteTKExample.page delete mode 100644 RemoteTKMobile.page delete mode 100644 TestRemoteTKController.cls diff --git a/README.markdown b/README.markdown index 92877d2..b10229f 100644 --- a/README.markdown +++ b/README.markdown @@ -6,16 +6,51 @@ This minimal toolkit allows JavaScript in web pages to call the Force.com REST A Background ---------- -Due to the [same origin policy](http://en.wikipedia.org/wiki/Same_origin_policy), JavaScript running in Visualforce pages may not use [XmlHttpRequest](http://en.wikipedia.org/wiki/XMLHttpRequest) to directly invoke the REST API, since Visualforce pages have hostnames of the form abc.na1.visual.force.com, and the REST API endpoints are of the form na1.salesforce.com. - -The RemoteTK Visualforce Custom Component (comprising RemoteTK.component and RemoteTKController.cls) provides an abstraction very similar to the REST API, implemented via `@RemoteAction` methods in the component's controller. The advantage of this mechanism is that no API calls are consumed. - -Alternatively, the ForceTK JavaScript library works around the same origin restriction by using the [AJAX Proxy](http://www.salesforce.com/us/developer/docs/ajax/Content/sforce_api_ajax_queryresultiterator.htm#ajax_proxy) to give full access to the REST API. Since the AJAX proxy is present on all -Visualforce hosts with an endpoint of the form https://abc.na1.visual.force.com/services/proxy, our Visualforce-hosted JavaScript can invoke it, passing the desired resource URL in an HTTP header. A drawback here is that using the REST API, even from a Visualforce page, consumes API calls. - -To host JavaScript *outside* the Force.com platform, we can deploy a simple PHP proxy to perform the same function as the AJAX proxy. - -[PhoneGap](http://www.phonegap.com/) provides a way for HTML5/JavaScript apps to run as native applications; in this configuration a proxy is not required - the toolkit simply provides a convenient abstraction of the REST API. +ForceTK provides a convenient, thin JavaScript abstraction of the [Force.com REST API](https://developer.salesforce.com/page/REST_API), making the API more accessible to JavaScript code running in Visualforce, in hybrid mobile apps, and elsewhere. + +Due to the [same origin policy](http://en.wikipedia.org/wiki/Same_origin_policy), JavaScript running outside the Force.com Platform may not use [XMLHttpRequest](http://en.wikipedia.org/wiki/XMLHttpRequest) to directly invoke the REST API, so a minimal PHP proxy is provided. + +Recent Updates +-------------- + +* [Visualforce Remote Objects](https://www.salesforce.com/us/developer/docs/pages/index_Left.htm#CSHID=pages_remote_objects.htm|StartTopic=Content%2Fpages_remote_objects.htm|SkinName=webhelp) are proxy objects that enable basic DML operations on sObjects directly from JavaScript. Behind the scenes, the Remote Objects controller handles sharing rules, field level security, and other data accessibility concerns. Pages that use Remote Objects are subject to all the standard Visualforce limits, but like JavaScript remoting, Remote Objects calls don’t count toward API request limits. + + + Since Remote Objects are more secure than RemoteTK (which does not respect sharing rules, FLS etc since system-level access is proxied via the RemoteTK controller), and similarly do not consume API calls (the main motivation for RemoteTK), RemoteTK has been removed from the toolkit. + +* Since the Summer '13 release, the `/services/data` endpoint has been exposed on Visualforce hosts, so no proxy is now required for REST API calls in JavaScript served via Visualforce (although the proxy **is** still required for calls to `/services/apexrest`). `forcetk.js` has been updated to reflect this. + +* Inserting or updating blob data using the `create` or `update` functions (passing base64-encoded binary data in JSON) is limited by the REST API to 50 MB of text data or 37.5 MB of base64–encoded data. New functions, `createBlob` and `updateBlob`, allow creation and update of ContentVersion and Document records with binary ('blob') content with a size of up to 500 MB. Here is a minimal sample that shows how to upload a file to Chatter Files: + + + +

+ Select a file to upload as a new Chatter File. +

+ +

+ +
+ + Under the covers, `createBlob` sends a multipart message. See the REST API doc page [Insert or Update Blob Data](https://www.salesforce.com/us/developer/docs/api_rest/Content/dome_sobject_insert_update_blob.htm) for more details. Dependencies ------------ @@ -25,37 +60,8 @@ The toolkit uses [jQuery](http://jquery.com/). It has been tested on jQuery 1.4. Configuration ------------- -RemoteTK requires no configuration. - ForceTK requires that you add the correct REST endpoint hostname for your instance (i.e. https://na1.salesforce.com/ or similar) as a remote site in *Your Name > Administration Setup > Security Controls > Remote Site Settings*. -Using RemoteTK in a Visualforce page ------------------------------------- - -Add RemoteTKController.cls and RemoteTK.component to your org by creating an Apex Class and a Component and pasting in the respective content, pasting the files into a [Force.com IDE](http://wiki.developerforce.com/page/Force.com_IDE) project, or by using the [Force.com Migration Tool](http://wiki.developerforce.com/page/Migration_Tool_Guide). - -Your Visualforce page will need to include the component and create a client object. An absolutely minimal sample is: - - - - - - -

The first account I see is .

-
- -More fully featured samples are provided in [RemoteTKExample.page](Force.com-JavaScript-REST-Toolkit/blob/master/RemoteTKExample.page) and [RemoteTKMobile.page](Force.com-JavaScript-REST-Toolkit/blob/master/RemoteTKMobile.page). - Using ForceTK in a Visualforce page ----------------------------------- @@ -67,15 +73,12 @@ Your Visualforce page will need to include jQuery and the toolkit, then create a

The first account I see is .

@@ -130,14 +133,14 @@ Your HTML page will need to include jQuery and the toolkit, then create a client function sessionCallback(oauthResponse) { if (typeof oauthResponse === 'undefined' || typeof oauthResponse['access_token'] === 'undefined') { - $('#message').html('Error - unauthorized!'); + $('#message').text('Error - unauthorized!'); } else { client.setSessionToken(oauthResponse.access_token, null, oauthResponse.instance_url); client.query("SELECT Name FROM Account LIMIT 1", function(response){ - $('#message').html('The first account I see is ' + $('#message').text('The first account I see is ' +response.records[0].Name); }); } @@ -215,7 +218,7 @@ An absolutely minimal sample using OAuth to obtain a session ID is: client.query("SELECT Name FROM Account LIMIT 1", function(response){ - $('#message').html('The first account I see is ' + $('#message').text('The first account I see is ' +response.records[0].Name); } ); diff --git a/RemoteTK.component b/RemoteTK.component deleted file mode 100644 index 071114a..0000000 --- a/RemoteTK.component +++ /dev/null @@ -1,201 +0,0 @@ - - - - \ No newline at end of file diff --git a/RemoteTKController.cls b/RemoteTKController.cls deleted file mode 100644 index 7e3419e..0000000 --- a/RemoteTKController.cls +++ /dev/null @@ -1,315 +0,0 @@ -/* - * Copyright (c) 2012, salesforce.com, inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, are permitted provided - * that the following conditions are met: - * - * Redistributions of source code must retain the above copyright notice, this list of conditions and the - * following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and - * the following disclaimer in the documentation and/or other materials provided with the distribution. - * - * Neither the name of salesforce.com, inc. nor the names of its contributors may be used to endorse or - * promote products derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A - * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED - * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -public class RemoteTKController { - private static String makeError(String message, String errorCode) { - JSONGenerator gen = JSON.createGenerator(false); - gen.writeStartArray(); - gen.writeStartObject(); - gen.writeStringField('message', message); - gen.writeStringField('errorCode', errorCode); - gen.writeEndObject(); - gen.writeEndArray(); - - return gen.getAsString(); - } - - private static String writeFields(String objtype, SObject obj, String fields) { - Map fieldMap = null; - try { - fieldMap = (Map)JSON.deserializeUntyped(fields); - } catch (JSONException je) { - return makeError(je.getMessage(), 'JSON_PARSER_ERROR'); - } - - Schema.SObjectType targetType = Schema.getGlobalDescribe().get(objtype); - - Map targetFields = targetType.getDescribe().fields.getMap(); - - try { - for (String key : fieldMap.keySet()) { - if (targetFields.get(key) == null) { - return '[{"message":"Field '+key+' does not exist on object type '+objtype+'","errorCode":"INVALID_FIELD"}]'; - } - - Object value = fieldMap.get(key); - Schema.DisplayType valueType = targetFields.get(key).getDescribe().getType(); - - if (value instanceof String && valueType != Schema.DisplayType.String) { - // Coerce an incoming String to the correct type - String svalue = (String)value; - - if (valueType == Schema.DisplayType.Date) { - obj.put(key, Date.valueOf(svalue)); - } else if (valueType == Schema.DisplayType.Percent || - valueType == Schema.DisplayType.Currency) { - obj.put(key, svalue == '' ? null : Decimal.valueOf(svalue)); - } else if (valueType == Schema.DisplayType.Double) { - obj.put(key, svalue == '' ? null : Double.valueOf(svalue)); - } else if (valueType == Schema.DisplayType.Integer) { - obj.put(key, Integer.valueOf(svalue)); - } else { - obj.put(key, svalue); - } - } else { - // Just try putting the incoming value on the object - obj.put(key, value); - } - } - } catch (SObjectException soe) { - return makeError(soe.getMessage(), 'INVALID_FIELD'); - } - - return null; - } - - private static List picklistOptions(Schema.DescribeFieldResult field) { - List picklistOptions = new List(); - Schema.DisplayType fieldType = field.getType(); - if (fieldType != Schema.DisplayType.Picklist && - fieldType != Schema.DisplayType.MultiPicklist && - fieldType != Schema.DisplayType.Combobox) { - return picklistOptions; - } - List picklistValues = field.getPicklistValues(); - for (Schema.PicklistEntry picklistValue: picklistValues) { - Map picklistOption = new Map(); - picklistOption.put('value', picklistValue.getValue()); - picklistOption.put('label', picklistValue.getValue()); - picklistOption.put('active', picklistValue.isActive()); - picklistOption.put('defaultValue', picklistValue.isDefaultValue()); - picklistOptions.add(picklistOption); - } - return picklistOptions; - } - - @remoteAction - public static String describe(String objtype) { - // Just enough to make the sample app work! - Schema.SObjectType targetType = Schema.getGlobalDescribe().get(objtype); - if (targetType == null) { - return makeError('The requested resource does not exist', 'NOT_FOUND'); - } - - Schema.DescribeSObjectResult sobjResult = targetType.getDescribe(); - - Map fieldMap = sobjResult.fields.getMap(); - - List fields = new List(); - for (String key : fieldMap.keySet()) { - Schema.DescribeFieldResult descField = fieldMap.get(key).getDescribe(); - Map field = new Map(); - - field.put('type', descField.getType().name().toLowerCase()); - field.put('name', descField.getName()); - field.put('label', descField.getLabel()); - List references = new List(); - for (Schema.sObjectType t: descField.getReferenceTo()) { - references.add(t.getDescribe().getName()); - } - if (!references.isEmpty()) { - field.put('referenceTo', references); - } - field.put('picklistValues', picklistOptions(descField)); - - fields.add(field); - } - - Map result = new Map(); - result.put('fields', fields); - - return JSON.serialize(result); - } - - @remoteAction - public static String create(String objtype, String fields) { - Schema.SObjectType targetType = Schema.getGlobalDescribe().get(objtype); - if (targetType == null) { - return makeError('The requested resource does not exist', 'NOT_FOUND'); - } - - SObject obj = targetType.newSObject(); - - String error = writeFields(objType, obj, fields); - if (error != null) { - return error; - } - - try { - insert obj; - } catch (DMLException dmle) { - String fieldNames = ''; - for (String field : dmle.getDmlFieldNames(0)) { - if (fieldNames.length() > 0) { - fieldNames += ','; - } - fieldNames += '"'+field+'"'; - } - return '[{"fields":['+fieldNames+'],"message":"'+dmle.getDmlMessage(0)+'","errorCode":"'+dmle.getDmlType(0).name()+'"}]'; - } - - Map result = new Map(); - result.put('id', obj.id); - result.put('errors', new List()); - result.put('success', true); - - return JSON.serialize(result); - } - - @remoteAction - public static String retrieve(String objtype, String id, String fieldlist) { - // TODO - handle null fieldlist - retrieve all fields - Boolean containsId = false; - for (String field : fieldlist.split(',')) { - if (field.equalsIgnoreCase('id')){ - containsId = true; - break; - } - } - - if (!containsId) { - fieldlist = 'Id,'+fieldlist; - } - - String soql = 'SELECT '+fieldlist+' FROM '+objtype+' WHERE Id = \''+id+'\''; - List records; - try { - records = Database.query(soql); - } catch (QueryException qe) { - return makeError(qe.getMessage(), 'INVALID_QUERY'); - } - - return JSON.serialize(records[0]); - } - - @remoteAction - public static String upser(String objtype, String externalIdField, String externalId, String fields) { - Schema.SObjectType targetType = Schema.getGlobalDescribe().get(objtype); - if (targetType == null) { - return makeError('The requested resource does not exist', 'NOT_FOUND'); - } - - SObject obj = targetType.newSObject(); - obj.put(externalIdField, externalId); - - String error = writeFields(objType, obj, fields); - if (error != null) { - return error; - } - - Schema.SObjectField sobjField = targetType.getDescribe().fields.getMap().get(externalIdField); - - Database.Upsert(obj, sobjField); - - return null; - } - - @remoteAction - public static String updat(String objtype, String id, String fields) { - Schema.SObjectType targetType = Schema.getGlobalDescribe().get(objtype); - if (targetType == null) { - return makeError('The requested resource does not exist', 'NOT_FOUND'); - } - - SObject obj = targetType.newSObject(id); - - String error = writeFields(objType, obj, fields); - if (error != null) { - return error; - } - - try { - update obj; - } catch (DMLException dmle) { - String fieldNames = ''; - for (String field : dmle.getDmlFieldNames(0)) { - if (fieldNames.length() > 0) { - fieldNames += ','; - } - fieldNames += '"'+field+'"'; - } - return '[{"fields":['+fieldNames+'],"message":"'+dmle.getDmlMessage(0)+'","errorCode":"'+dmle.getDmlType(0).name()+'"}]'; - } - - return null; - } - - @remoteAction - public static String del(String objtype, String id) { - Schema.SObjectType targetType = Schema.getGlobalDescribe().get(objtype); - if (targetType == null) { - return makeError('The requested resource does not exist', 'NOT_FOUND'); - } - - SObject obj = targetType.newSObject(id); - - try { - delete obj; - } catch (DMLException dmle) { - String fieldNames = ''; - for (String field : dmle.getDmlFieldNames(0)) { - if (fieldNames.length() > 0) { - fieldNames += ','; - } - fieldNames += '"'+field+'"'; - } - return '[{"fields":['+fieldNames+'],"message":"'+dmle.getDmlMessage(0)+'","errorCode":"'+dmle.getDmlType(0).name()+'"}]'; - } - - return null; - } - - @remoteAction - public static String query(String soql) { - List records; - try { - records = Database.query(soql); - } catch (QueryException qe) { - return makeError(qe.getMessage(), 'INVALID_QUERY'); - } - - Map result = new Map(); - result.put('records', records); - result.put('totalSize', records.size()); - result.put('done', true); - - return JSON.serialize(result); - } - - @remoteAction - public static String search(String sosl) { - List> result; - try { - result = Search.query(sosl); - } catch (QueryException qe) { - return makeError(qe.getMessage(), 'INVALID_SEARCH'); - } catch (SearchException se) { - return makeError(se.getMessage(), 'INVALID_SEARCH'); - } - - return JSON.serialize(result); - } -} \ No newline at end of file diff --git a/RemoteTKExample.page b/RemoteTKExample.page deleted file mode 100644 index 2b89192..0000000 --- a/RemoteTKExample.page +++ /dev/null @@ -1,150 +0,0 @@ - - - - - - - - Force.com JavaScript REST Toolkit - - - - - - - - - - - -
-
-
-
-
-
- - - - - - - - - -
\ No newline at end of file diff --git a/RemoteTKMobile.page b/RemoteTKMobile.page deleted file mode 100644 index 25e9673..0000000 --- a/RemoteTKMobile.page +++ /dev/null @@ -1,144 +0,0 @@ - - - - -"}"/> - - - - -Accounts - - - - - - - - - - - -
- -
-

Account List

-
-
-
- -
-
    -
-
-
-

Some Text

-
-
-
-
-

Account Detail

-
-
- - - - -
Account Name:
Industry:
Ticker Symbol:
-
- - - -
-
-
-

Some Text

-
-
-
-
-

New Account

-
-
-
- - - - - - - - - - - - - - -
Account Name:
Industry:
Ticker Symbol:
- -
-
-
-

Some Text

-
-
- - -
\ No newline at end of file diff --git a/TestRemoteTKController.cls b/TestRemoteTKController.cls deleted file mode 100644 index daade25..0000000 --- a/TestRemoteTKController.cls +++ /dev/null @@ -1,306 +0,0 @@ -@isTest -public class TestRemoteTKController{ - private static String tooLongAccName = 'LOTS OF '+ - 'CHARACTERS XXXXXXXXXXXXXXXXXXXXXXXX'+ - 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'+ - 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'+ - 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'+ - 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'+ - 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'+ - 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'+ - 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'+ - 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'+ - 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'+ - 'XXXXXXXXXXXXXXXX'; - - static private void assertError(String jsonResult, String expectedError, String method) { - List errorArray = (List)JSON.deserializeUntyped(jsonResult); - - System.assertNotEquals(null, errorArray, - 'error array missing from '+method+' result'); - System.assertNotEquals(0, errorArray.size(), - 'error array is empty in '+method+' result'); - - Map error = (Map)errorArray[0]; - String errorCode = (String)error.get('errorCode'); - System.assertNotEquals(null, errorCode, - 'errorCode property missing from '+method+' result'); - System.assertEquals(expectedError, errorCode, - 'errorCode should be '+expectedError+' in '+method+' result'); - } - - static testMethod void testDescribe() { - // Assume we have accounts - String jsonResult = RemoteTKController.describe('Account'); - - System.assertNotEquals(null, jsonResult, - 'RemoteTKController.describe returned null'); - - Map result = (Map)JSON.deserializeUntyped(jsonResult); - - System.assertNotEquals(null, result.get('fields'), - 'fields property missing from RemoteTKController.describe result'); - - // TODO - more assertions on describe results - - // Invalid object type - // Hope there isn't a QXZXQZXZQXZQ object type! - jsonResult = RemoteTKController.describe('QXZXQZXZQXZQ'); - assertError(jsonResult, 'NOT_FOUND', 'RemoteTKController.describe'); - } - - static private void assertRecord(Map record, String accName, String accNumber, String method) { - Map attributes = (Map)record.get('attributes'); - System.assertNotEquals(null, attributes, - 'attributes property missing from '+method+' result'); - System.assertNotEquals(0, attributes.keySet().size(), - 'empty attributes object in '+method+' result'); - - String type = (String)attributes.get('type'); - System.assertNotEquals(null, type, - 'type property missing from '+method+' result'); - System.assertEquals('Account', type, - 'Wrong type in '+method+' result'); - - String url = (String)attributes.get('url'); - System.assertNotEquals(null, url, - 'url property missing from '+method+' result'); - - Id id = (Id)record.get('Id'); - System.assertNotEquals(null, id, - 'Id property missing from '+method+' result'); - Account account = [SELECT Id, Name FROM Account WHERE Id = :id LIMIT 1]; - System.assertNotEquals(null, account, - 'Couldn\'t find account record identified by '+method+' result'); - System.assertEquals(accName, account.Name, - 'Account name doesn\'t match in '+method+' result'); - - String name = (String)record.get('Name'); - System.assertNotEquals(null, name, - 'Name property missing from '+method+' result'); - System.assertEquals(accName, name, - 'Wrong account name in '+method+' result'); - - String accountNumber = (String)record.get('AccountNumber'); - System.assertNotEquals(null, name, - 'AccountNumber property missing from '+method+' result'); - System.assertEquals(accNumber, accountNumber, - 'Wrong account number in '+method+' result'); - } - - static private Id testCreate(String accName, String accNumber, String fields) { - // Assume we can create an account - - // Try with data in correct types - String jsonResult = RemoteTKController.create('Account', - '{"Name": "'+accName+'", '+ - '"AccountNumber" : "'+accNumber+'",'+ - fields+'}'); - - System.assertNotEquals(null, jsonResult, - 'RemoteTKController.create returned null'); - - Map result = (Map)JSON.deserializeUntyped(jsonResult); - - Boolean success = (Boolean)result.get('success'); - System.assertNotEquals(null, success, - 'success property missing from RemoteTKController.create result'); - System.assertNotEquals(false, success, - 'success is false in RemoteTKController.create result'); - - List errors = (List)result.get('errors'); - System.assertNotEquals(null, errors, - 'errors property missing from RemoteTKController.create result'); - System.assertEquals(0, errors.size(), - 'errors array is not empty in RemoteTKController.create result'); - - Id id = (Id)result.get('id'); - System.assertNotEquals(null, id, - 'id property missing from RemoteTKController.create result'); - Account account = [SELECT Id, Name, AccountNumber FROM Account LIMIT 1]; - System.assertNotEquals(null, account, - 'Couldn\'t find account record created by RemoteTKController.create result'); - System.assertEquals(accName, account.Name, - 'Account name doesn\'t match in RemoteTKController.create result'); - System.assertEquals(accNumber, account.AccountNumber, - 'Account number doesn\'t match in RemoteTKController.create result'); - - jsonResult = RemoteTKController.create('QXZXQZXZQXZQ', '{"Name": "'+accName+'"}'); - assertError(jsonResult, 'NOT_FOUND', 'RemoteTKController.create'); - - jsonResult = RemoteTKController.create('Account', '{"Name" "'+accName+'"}'); - assertError(jsonResult, 'JSON_PARSER_ERROR', 'RemoteTKController.create'); - - jsonResult = RemoteTKController.create('Account', '{"XQZXQZXQZXQZ" : "'+accName+'"}'); - assertError(jsonResult, 'INVALID_FIELD', 'RemoteTKController.create'); - - jsonResult = RemoteTKController.create('Account', '{"Name" : "'+tooLongAccName+'"}'); - assertError(jsonResult, 'STRING_TOO_LONG', 'RemoteTKController.create'); - - return id; - } - - static private void testRetrieve(String accName, String accNumber, Id id) { - String jsonResult = RemoteTKController.retrieve('Account', id, 'Name, AccountNumber'); - - System.assertNotEquals(null, jsonResult, - 'RemoteTKController.retrieve returned null'); - - Map result = (Map)JSON.deserializeUntyped(jsonResult); - - assertRecord(result, accName, accNumber, 'RemoteTKController.retrieve'); - - // TODO - test negative paths for retrieve - } - - static private void testQuery(String accName, String accNumber) { - String jsonResult = RemoteTKController.query('SELECT Id, Name, AccountNumber FROM Account WHERE Name = \''+accName+'\''); - - System.assertNotEquals(null, jsonResult, - 'RemoteTKController.query returned null'); - - Map result = (Map)JSON.deserializeUntyped(jsonResult); - - List records = (List)result.get('records'); - System.assertNotEquals(null, records, - 'records property missing from RemoteTKController.query result'); - System.assertEquals(1, records.size(), - 'records array should have single record in RemoteTKController.query result'); - - Map record = (Map)records[0]; - - assertRecord(record, accName, accNumber, 'RemoteTKController.query'); - - Integer totalSize = (Integer)result.get('totalSize'); - System.assertNotEquals(null, totalSize, - 'totalSize property missing from RemoteTKController.query result'); - System.assertEquals(1, totalSize, - 'totalSize should be 1 in RemoteTKController.query result'); - - Boolean done = (Boolean)result.get('done'); - System.assertNotEquals(null, done, - 'done property missing from RemoteTKController.query result'); - System.assertEquals(true, done, - 'done should be true in RemoteTKController.query result'); - - jsonResult = RemoteTKController.query('SSSSSS Id, Name FROM Account WHERE Name = \''+accName+'\''); - assertError(jsonResult, 'INVALID_QUERY', 'RemoteTKController.query'); - } - - static private void testSearch(String accName, String accNumber, Id id) { - Id [] fixedSearchResults= new Id[1]; - fixedSearchResults[0] = id; - Test.setFixedSearchResults(fixedSearchResults); - String jsonResult = RemoteTKController.search('FIND {'+accName+'} IN ALL FIELDS RETURNING Account (Id, Name, AccountNumber)'); - - System.assertNotEquals(null, jsonResult, - 'RemoteTKController.search returned null'); - - List result = (List)JSON.deserializeUntyped(jsonResult); - - List records = (List)result[0]; - - Map record = (Map)records[0]; - - assertRecord(record, accName, accNumber, 'RemoteTKController.search'); - - jsonResult = RemoteTKController.search('FFFF {'+accName+'} IN ALL FIELDS RETURNING Account (Id, Name)'); - assertError(jsonResult, 'INVALID_SEARCH', 'RemoteTKController.search'); - } - - static private void testUpdate(String accName, String accNumber, Id id, String fields) { - String jsonResult = RemoteTKController.updat('Account', id, '{"Name":"'+accName+'", "AccountNumber":"'+accNumber+'"}'); - System.assertEquals(null, jsonResult, - 'Non-null result from RemoteTKController.updat'); - Account account = [SELECT Id, Name, AccountNumber FROM Account WHERE Id = :id LIMIT 1]; - System.assertNotEquals(null, account, - 'Couldn\'t find account record after RemoteTKController.updat'); - System.assertEquals(accName, account.Name, - 'Account name doesn\'t match after RemoteTKController.updat'); - System.assertEquals(accNumber, account.AccountNumber, - 'Account number doesn\'t match after RemoteTKController.updat'); - - jsonResult = RemoteTKController.updat('QXZXQZXZQXZQ', id, '{"Name":"'+accName+'"}'); - assertError(jsonResult, 'NOT_FOUND', 'RemoteTKController.updat'); - - jsonResult = RemoteTKController.updat('Account', id, '{"XQZXQZXQZXQZ" : "'+accName+'"}'); - assertError(jsonResult, 'INVALID_FIELD', 'RemoteTKController.updat'); - - jsonResult = RemoteTKController.updat('Account', id, '{"Name" "'+accName+'"}'); - assertError(jsonResult, 'JSON_PARSER_ERROR', 'RemoteTKController.updat'); - - jsonResult = RemoteTKController.updat('Account', id, '{"Name" : "'+tooLongAccName+'"}'); - assertError(jsonResult, 'STRING_TOO_LONG', 'RemoteTKController.updat'); - } - - static private void testUpsert(String accName, String accNumber, Id id, String fields) { - String jsonResult = RemoteTKController.upser('Account', - 'Id', - (String)id, - '{"Name":"'+accName+'", '+ - '"AccountNumber":"'+accNumber+'",'+ - fields+'}'); - System.assertEquals(null, jsonResult, - 'Non-null result from RemoteTKController.upser'); - Account account = [SELECT Id, Name, AccountNumber FROM Account WHERE Id = :id LIMIT 1]; - System.assertNotEquals(null, account, - 'Couldn\'t find account record after RemoteTKController.upser'); - System.assertEquals(accName, account.Name, - 'Account name doesn\'t match after RemoteTKController.upser'); - System.assertEquals(accNumber, account.AccountNumber, - 'Account number doesn\'t match after RemoteTKController.upser'); - - jsonResult = RemoteTKController.upser('QXZXQZXZQXZQ', 'Id', (String)id, '{"Name":"'+accName+'"}'); - assertError(jsonResult, 'NOT_FOUND', 'RemoteTKController.upser'); - - jsonResult = RemoteTKController.upser('Account', 'Id', (String)id, '{"XQZXQZXQZXQZ" : "'+accName+'"}'); - assertError(jsonResult, 'INVALID_FIELD', 'RemoteTKController.upser'); - } - - static private void testDelete(Id id) { - String jsonResult = RemoteTKController.del('QXZXQZXZQXZQ', id); - assertError(jsonResult, 'NOT_FOUND', 'RemoteTKController.del'); - - jsonResult = RemoteTKController.del('Account', id); - System.assertEquals(null, jsonResult, - 'Non-null result from RemoteTKController.del'); - List accounts = [SELECT Id, Name FROM Account WHERE Id = :id]; - System.assertEquals(0, accounts.size(), - 'Account record was not deleted by RemoteTKController.del'); - - jsonResult = RemoteTKController.del('Account', id); - assertError(jsonResult, 'ENTITY_IS_DELETED', 'RemoteTKController.del'); - } - - static testMethod void testCRUD() { - String accName = 'Test1'; - String accNumber = '1234'; - - // String field values - Id id = testCreate(accName, accNumber, '"AnnualRevenue" : "1000000",'+ - '"NumberOfEmployees" : "1000",'+ - '"Phone" : "(111) 222-3333"'); - testDelete(id); - - // Integer field values - id = testCreate(accName, accNumber, '"AnnualRevenue" : 1000000,'+ - '"NumberOfEmployees" : 1000,'+ - '"Phone" : "(111) 222-3333"'); - testRetrieve(accName, accNumber, id); - testQuery(accName, accNumber); - testSearch(accName, accNumber, id); - testUpdate(accName+'1', accNumber+'1', id, '"AnnualRevenue" : "1100000",'+ - '"NumberOfEmployees" : "1100",'+ - '"Phone" : "(112) 222-3333"'); - testUpdate(accName+'2', accNumber+'2', id, '"AnnualRevenue" : "2000000",'+ - '"NumberOfEmployees" : "2000",'+ - '"Phone" : "(222) 222-3333"'); - testUpsert(accName+'3', accNumber+'3', id, '"AnnualRevenue" : 3000000,'+ - '"NumberOfEmployees" : 3000,'+ - '"Phone" : "(333) 222-3333"'); - testUpsert(accName+'4', accNumber+'4', id, '"AnnualRevenue" : 4000000,'+ - '"NumberOfEmployees" : 4000,'+ - '"Phone" : "(444) 222-3333"'); - testDelete(id); - } -} \ No newline at end of file diff --git a/app.js b/app.js index 10b7064..7ce5297 100644 --- a/app.js +++ b/app.js @@ -51,18 +51,18 @@ function metadataCallback(response){ // Using TrimPath Template for now - may switch to jQuery Template at some // point - $j('#prompt').html(TrimPath.processDOMTemplate("prompt_jst" + $('#prompt').html(TrimPath.processDOMTemplate("prompt_jst" , response)); // Set up autocomplete - $j( "#value" ).autocomplete({ + $( "#value" ).autocomplete({ source: function( request, response ) { var query = "SELECT Id, Name FROM Account "+ - "WHERE "+$j("#field").val()+" LIKE '%"+request.term+"%' "+ + "WHERE "+$("#field").val()+" LIKE '%"+request.term+"%' "+ "ORDER BY Name LIMIT 20"; client.query(query, function( data ) { - response( $j.map( data.records, function( record ) { + response( $.map( data.records, function( record ) { return { label: record.Name, value: record.Id @@ -76,22 +76,22 @@ if ( ui.item != null ) { showAccountDetail(ui.item.value); } else { - filterAccounts($j("#field").val(),this.value); + filterAccounts($("#field").val(),this.value); } return false; }, }); - $j('#go').click(function(e) { - var field = $j("#field").val(); - var value = $j("#value").val(); + $('#go').click(function(e) { + var field = $("#field").val(); + var value = $("#value").val(); e.preventDefault(); filterAccounts(field,value); }); - $j('#new').click(function(e) { + $('#new').click(function(e) { e.preventDefault(); // Just make Trimpath happy @@ -101,19 +101,19 @@ dummy[response.fields[i].name] = ''; } $dialog.html(TrimPath.processDOMTemplate("edit_jst", dummy)); - $dialog.find('#action').html('Create').click(function(e) { + $dialog.find('#action').text('Create').click(function(e) { e.preventDefault(); $dialog.dialog('close'); var fields = {}; $dialog.find('input').each(function() { - var child = $j(this); + var child = $(this); if ( child.val().length > 0 ) { fields[child.attr("name")] = child.val(); } }); - $j('#list').html(ajaxgif+" creating account..."); + $('#list').html(ajaxgif+" creating account..."); client.create('Account', fields, createCallback, errorCallback); }); @@ -125,21 +125,21 @@ } function queryCallback(response) { - $j('#list').html(TrimPath.processDOMTemplate("accounts_jst" + $('#list').html(TrimPath.processDOMTemplate("accounts_jst" , response)); - $j('#version').html($j.fn.jquery); - $j('#uiversion').html($j.ui.version); + $('#version').text($.fn.jquery); + $('#uiversion').text($.ui.version); - $j("#list tr:nth-child(odd)").addClass("odd"); + $("#list tr:nth-child(odd)").addClass("odd"); - $j('#logout').click(logout); + $('#logout').click(logout); - $j('#accounts').find('.id') + $('#accounts').find('.id') .hover(function() { - $j(this).addClass("highlighted"); + $(this).addClass("highlighted"); },function(){ - $j(this).removeClass("highlighted"); + $(this).removeClass("highlighted"); }) .click(function(){ showAccountDetail(this.id); @@ -156,36 +156,36 @@ && !response.Website.startsWith('http://')) { response.Website = 'http://'+response.Website; } - $dialog.html(TrimPath.processDOMTemplate("detail_jst" + $dialog.TrimPath.processDOMTemplate("detail_jst" ,response)); $dialog.find('#industry').click(function(e) { e.preventDefault(); $dialog.dialog('close'); - filterIndustry($j(this).html()); + filterIndustry($(this).text()); }); $dialog.find('#delete').click(function(e) { e.preventDefault(); $dialog.dialog('close'); - $j('#list').html(ajaxgif+" deleting account..."); + $('#list').html(ajaxgif+" deleting account..."); client.del('Account', $dialog.find('#id').val(), deleteCallback, errorCallback); }); $dialog.find('#edit').click(function(e) { e.preventDefault(); $dialog.html(TrimPath.processDOMTemplate("edit_jst" ,response)); - $dialog.find('#action').html('Update').click(function(e) { + $dialog.find('#action').text('Update').click(function(e) { e.preventDefault(); $dialog.dialog('close'); var fields = {}; $dialog.find('input').each(function() { - var child = $j(this); + var child = $(this); if ( child.val().length > 0 && child.attr("name") != 'id') { fields[child.attr("name")] = child.val(); } }); - $j('#list').html(ajaxgif+" updating account..."); + $('#list').html(ajaxgif+" updating account..."); client.update('Account', $dialog.find('#id').val(), fields, updateCallback, errorCallback); }); @@ -193,19 +193,19 @@ } function createCallback(response) { - $j('#list').html('Created '+response.id); + $('#list').text('Created '+response.id); setTimeout("filterAccounts()",1000); } function updateCallback(response) { - $j('#list').html('Updated'); + $('#list').text('Updated'); setTimeout("filterAccounts()",1000); } function deleteCallback(response) { - $j('#list').html('Deleted'); + $('#list').text('Deleted'); setTimeout("filterAccounts()",1000); } @@ -222,7 +222,7 @@ } function filterIndustry(industry) { - $j('#list').html(ajaxgif+" loading data..."); + $('#list').html(ajaxgif+" loading data..."); var query = "SELECT Id, Name FROM Account WHERE Industry = '"+industry +"' ORDER BY Name LIMIT 20"; @@ -231,7 +231,7 @@ } function filterAccounts(field, value) { - $j('#list').html(ajaxgif+" loading data..."); + $('#list').html(ajaxgif+" loading data..."); var query = ( typeof value !== 'undefined' && value.length > 0 ) ? "SELECT Id, Name FROM Account WHERE "+field+" LIKE '%"+value diff --git a/example.html b/example.html index 1af86b9..f5439d4 100644 --- a/example.html +++ b/example.html @@ -76,13 +76,8 @@ var $dialog = null; - // We use $j rather than $ for jQuery - if (window.$j === undefined) { - $j = $; - } - - $j(document).ready(function() { - $j('#login').popupWindow({ + $(document).ready(function() { + $('#login').popupWindow({ windowURL: getAuthorizeUrl(loginUrl, clientId, redirectUri), windowName: 'Connect', centerBrowser: 1, @@ -90,7 +85,7 @@ width:675 }); - $dialog = $j('
') + $dialog = $('
') .dialog({ autoOpen: false, width: 450 @@ -104,13 +99,12 @@ } function hideButton(){ - $j('#connect').html(ajaxgif+" connecting..."); + $('#connect').text(ajaxgif+" connecting..."); } function sessionCallback(oauthResponse) { if (typeof oauthResponse === 'undefined' || typeof oauthResponse['access_token'] === 'undefined') { - //$j('#prompt').html('Error - unauthorized!'); errorCallback({ status: 0, statusText: 'Unauthorized', @@ -121,7 +115,7 @@ oauthResponse.instance_url); // Kick things off by doing a describe on Account... - $j('#prompt').html(ajaxgif+" loading metadata..."); + $('#prompt').text(ajaxgif+" loading metadata..."); client.describe('Account',metadataCallback, errorCallback); } } diff --git a/example.page b/example.page index e18b827..7ce51a7 100644 --- a/example.page +++ b/example.page @@ -48,9 +48,6 @@ Sample Visualforce page for Force.com JavaScript REST Toolkit * It must go in the VF page so that merge variables are processed. */ - // Get a reference to jQuery that we can work with - $j = jQuery.noConflict(); - // Get an instance of the REST API client and set the session ID var client = new forcetk.Client(); client.setSessionToken('{!$Api.Session_ID}'); @@ -59,16 +56,16 @@ Sample Visualforce page for Force.com JavaScript REST Toolkit var $dialog = null; - $j(document).ready(function() { + $(document).ready(function() { // Set up the dialog - $dialog = $j('
') + $dialog = $('
') .dialog({ autoOpen: false, width: 450 }); // Kick things off by doing a describe on Account... - $j('#prompt').html(ajaxgif+" loading metadata..."); + $('#prompt').html(ajaxgif+" loading metadata..."); client.describe('Account', metadataCallback); }); diff --git a/forcetk.js b/forcetk.js index 3b94914..57d19a2 100644 --- a/forcetk.js +++ b/forcetk.js @@ -40,11 +40,6 @@ if (forcetk === undefined) { if (forcetk.Client === undefined) { - // We use $j rather than $ for jQuery so it works in Visualforce - if (window.$j === undefined) { - $j = $; - } - /** * The Client provides a convenient wrapper for the Force.com REST API, * allowing JavaScript in Visualforce pages to use the API via the Ajax @@ -63,7 +58,7 @@ if (forcetk.Client === undefined) { // In PhoneGap this.proxyUrl = null; } else { - // In Visualforce + // In Visualforce - still need proxyUrl for Apex REST methods this.proxyUrl = location.protocol + "//" + location.hostname + "/services/proxy"; } @@ -76,6 +71,7 @@ if (forcetk.Client === undefined) { this.refreshToken = null; this.sessionId = null; this.apiVersion = null; + this.visualforce = false; this.instanceUrl = null; this.asyncAjax = true; } @@ -96,9 +92,9 @@ if (forcetk.Client === undefined) { forcetk.Client.prototype.refreshAccessToken = function(callback, error) { var that = this; var url = this.loginUrl + '/services/oauth2/token'; - return $j.ajax({ + return $.ajax({ type: 'POST', - url: (this.proxyUrl !== null) ? this.proxyUrl: url, + url: (this.proxyUrl !== null && ! this.visualforce) ? this.proxyUrl: url, cache: false, processData: false, data: 'grant_type=refresh_token&client_id=' + this.clientId + '&refresh_token=' + this.refreshToken, @@ -106,7 +102,7 @@ if (forcetk.Client === undefined) { error: error, dataType: "json", beforeSend: function(xhr) { - if (that.proxyUrl !== null) { + if (that.proxyUrl !== null && ! this.visualforce) { xhr.setRequestHeader('SalesforceProxy-Endpoint', url); } } @@ -117,15 +113,17 @@ if (forcetk.Client === undefined) { * Set a session token and the associated metadata in the client. * @param sessionId a salesforce.com session ID. In a Visualforce page, * use '{!$Api.sessionId}' to obtain a session ID. - * @param [apiVersion="21.0"] Force.com API version + * @param [apiVersion="v29.0"] Force.com API version * @param [instanceUrl] Omit this if running on Visualforce; otherwise * use the value from the OAuth token. */ forcetk.Client.prototype.setSessionToken = function(sessionId, apiVersion, instanceUrl) { this.sessionId = sessionId; this.apiVersion = (typeof apiVersion === 'undefined' || apiVersion === null) - ? 'v27.0': apiVersion; + ? 'v29.0': apiVersion; if (typeof instanceUrl === 'undefined' || instanceUrl == null) { + this.visualforce = true; + // location.hostname can be of the form 'abc.na1.visual.force.com', // 'na1.salesforce.com' or 'abc.my.salesforce.com' (custom domains). // Split on '.', and take the [1] or [0] element as appropriate @@ -156,12 +154,12 @@ if (forcetk.Client === undefined) { */ forcetk.Client.prototype.ajax = function(path, callback, error, method, payload, retry) { var that = this; - var url = this.instanceUrl + '/services/data' + path; + var url = (this.visualforce ? '' : this.instanceUrl) + '/services/data' + path; - return $j.ajax({ + return $.ajax({ type: method || "GET", async: this.asyncAjax, - url: (this.proxyUrl !== null) ? this.proxyUrl: url, + url: (this.proxyUrl !== null && ! this.visualforce) ? this.proxyUrl: url, contentType: method == "DELETE" ? null : 'application/json', cache: false, processData: false, @@ -181,10 +179,10 @@ if (forcetk.Client === undefined) { }, dataType: "json", beforeSend: function(xhr) { - if (that.proxyUrl !== null) { + if (that.proxyUrl !== null && ! that.visualforce) { xhr.setRequestHeader('SalesforceProxy-Endpoint', url); } - xhr.setRequestHeader(that.authzHeader, "OAuth " + that.sessionId); + xhr.setRequestHeader(that.authzHeader, "Bearer " + that.sessionId); xhr.setRequestHeader('X-User-Agent', 'salesforce-toolkit-rest-javascript/' + that.apiVersion); } }); @@ -200,20 +198,20 @@ if (forcetk.Client === undefined) { * @param mimetype of the file * @param callback function to which response will be passed * @param [error=null] function to which request will be passed in case of error - * @param rety true if we've already tried refresh token flow once + * @param retry true if we've already tried refresh token flow once **/ forcetk.Client.prototype.getChatterFile = function(path,mimeType,callback,error,retry) { var that = this; - var url = this.instanceUrl + path; + var url = (this.visualforce ? '' : this.instanceUrl) + path; var request = new XMLHttpRequest(); - request.open("GET", (this.proxyUrl !== null) ? this.proxyUrl: url, true); + request.open("GET", (this.proxyUrl !== null && ! this.visualforce) ? this.proxyUrl: url, true); request.responseType = "arraybuffer"; - request.setRequestHeader(that.authzHeader, "OAuth " + that.sessionId); - request.setRequestHeader('X-User-Agent', 'salesforce-toolkit-rest-javascript/' + that.apiVersion); - if (this.proxyUrl !== null) { + request.setRequestHeader(this.authzHeader, "Bearer " + this.sessionId); + request.setRequestHeader('X-User-Agent', 'salesforce-toolkit-rest-javascript/' + this.apiVersion); + if (this.proxyUrl !== null && ! this.visualforce) { request.setRequestHeader('SalesforceProxy-Endpoint', url); } @@ -250,6 +248,124 @@ if (forcetk.Client === undefined) { request.send(); } + + // Local utility to create a random string for multipart boundary + function randomString() { + var str = ''; + for (var i = 0; i < 4; i++) { + str += (Math.random().toString(16)+"000000000").substr(2,8); + } + return str; + } + + /* Low level function to create/update records with blob data + * @param path resource path relative to /services/data + * @param fields an object containing initial field names and values for + * the record, e.g. {ContentDocumentId: "069D00000000so2", + * PathOnClient: "Q1 Sales Brochure.pdf"} + * @param filename filename for blob data; e.g. "Q1 Sales Brochure.pdf" + * @param payloadField 'VersionData' for ContentVersion, 'Body' for Document + * @param payload Blob, File, ArrayBuffer (Typed Array), or String payload + * @param callback function to which response will be passed + * @param [error=null] function to which response will be passed in case of error + * @param retry true if we've already tried refresh token flow once + */ + forcetk.Client.prototype.blob = function(path, fields, filename, payloadField, payload, callback, error, retry) { + var that = this; + var url = (this.visualforce ? '' : this.instanceUrl) + '/services/data' + path; + var boundary = randomString(); + + var blob = new Blob([ + "--boundary_" + boundary + '\n' + + "Content-Disposition: form-data; name=\"entity_content\";" + "\n" + + "Content-Type: application/json" + "\n\n" + + JSON.stringify(fields) + + "\n\n" + + "--boundary_" + boundary + "\n" + + "Content-Type: application/octet-stream" + "\n" + + "Content-Disposition: form-data; name=\"" + payloadField + + "\"; filename=\"" + filename + "\"\n\n", + payload, + "\n\n" + + "--boundary_" + boundary + "--" + ], {type : 'multipart/form-data; boundary=\"boundary_' + boundary + '\"'}); + + var request = new XMLHttpRequest(); + request.open("POST", (this.proxyUrl !== null && ! this.visualforce) ? this.proxyUrl: url, this.asyncAjax); + + request.setRequestHeader(this.authzHeader, "Bearer " + this.sessionId); + request.setRequestHeader('X-User-Agent', 'salesforce-toolkit-rest-javascript/' + this.apiVersion); + if (this.proxyUrl !== null && ! this.visualforce) { + request.setRequestHeader('SalesforceProxy-Endpoint', url); + } + + if (this.asyncAjax) { + request.onreadystatechange = function() { + // continue if the process is completed + if (request.readyState == 4) { + // continue only if HTTP status is good + if (request.status >= 200 && request.status < 300) { + // retrieve the response + callback(request.response ? JSON.parse(request.response) : null); + } else if(request.status == 401 && !retry) { + that.refreshAccessToken(function(oauthResponse) { + that.setSessionToken(oauthResponse.access_token, null,oauthResponse.instance_url); + that.blob(path, fields, fileName, file, callback, error, true); + }, + error); + } else { + // return status message + error(request, request.statusText, request.response); + } + } + } + } + + request.send(blob); + + return this.asyncAjax ? JSON.parse(request.response) : null; + } + + /* + * Create a record with blob data + * @param objtype object type; e.g. "ContentVersion" + * @param fields an object containing initial field names and values for + * the record, e.g. {ContentDocumentId: "069D00000000so2", + * PathOnClient: "Q1 Sales Brochure.pdf"} + * @param filename filename for blob data; e.g. "Q1 Sales Brochure.pdf" + * @param payloadField 'VersionData' for ContentVersion, 'Body' for Document + * @param payload Blob, File, ArrayBuffer (Typed Array), or String payload + * @param callback function to which response will be passed + * @param [error=null] function to which response will be passed in case of error + * @param retry true if we've already tried refresh token flow once + */ + forcetk.Client.prototype.createBlob = function(objtype, fields, filename, + payloadField, payload, callback, + error, retry) { + return this.blob('/' + this.apiVersion + '/sobjects/' + objtype + '/', + fields, filename, payloadField, payload, callback, error); + } + + /* + * Update a record with blob data + * @param objtype object type; e.g. "ContentVersion" + * @param id the record's object ID + * @param fields an object containing initial field names and values for + * the record, e.g. {ContentDocumentId: "069D00000000so2", + * PathOnClient: "Q1 Sales Brochure.pdf"} + * @param filename filename for blob data; e.g. "Q1 Sales Brochure.pdf" + * @param payloadField 'VersionData' for ContentVersion, 'Body' for Document + * @param payload Blob, File, ArrayBuffer (Typed Array), or String payload + * @param callback function to which response will be passed + * @param [error=null] function to which response will be passed in case of error + * @param retry true if we've already tried refresh token flow once + */ + forcetk.Client.prototype.updateBlob = function(objtype, id, fields, filename, + payloadField, payload, callback, + error, retry) { + return this.blob('/' + this.apiVersion + '/sobjects/' + objtype + '/' + id + + '?_HttpMethod=PATCH', fields, filename, payloadField, payload, callback, error); + } /* * Low level utility function to call the Salesforce endpoint specific for Apex REST API. @@ -258,14 +374,14 @@ if (forcetk.Client === undefined) { * @param [error=null] function to which jqXHR will be passed in case of error * @param [method="GET"] HTTP method for call * @param [payload=null] payload for POST/PATCH etc - * @param [paramMap={}] parameters to send as header values for POST/PATCH etc - * @param [retry] specifies whether to retry on error + * @param [paramMap={}] parameters to send as header values for POST/PATCH etc + * @param [retry] specifies whether to retry on error */ forcetk.Client.prototype.apexrest = function(path, callback, error, method, payload, paramMap, retry) { var that = this; var url = this.instanceUrl + '/services/apexrest' + path; - return $j.ajax({ + return $.ajax({ type: method || "GET", async: this.asyncAjax, url: (this.proxyUrl !== null) ? this.proxyUrl: url, @@ -291,14 +407,14 @@ if (forcetk.Client === undefined) { if (that.proxyUrl !== null) { xhr.setRequestHeader('SalesforceProxy-Endpoint', url); } - //Add any custom headers - if (paramMap === null) { - paramMap = {}; - } - for (paramName in paramMap) { - xhr.setRequestHeader(paramName, paramMap[paramName]); - } - xhr.setRequestHeader(that.authzHeader, "OAuth " + that.sessionId); + //Add any custom headers + if (paramMap === null) { + paramMap = {}; + } + for (paramName in paramMap) { + xhr.setRequestHeader(paramName, paramMap[paramName]); + } + xhr.setRequestHeader(that.authzHeader, "Bearer " + that.sessionId); xhr.setRequestHeader('X-User-Agent', 'salesforce-toolkit-rest-javascript/' + that.apiVersion); } }); @@ -465,9 +581,9 @@ if (forcetk.Client === undefined) { var index = url.indexOf( serviceData ); if( index > -1 ){ - url = url.substr( index + serviceData.length ); + url = url.substr( index + serviceData.length ); } else { - //-- leave alone + //-- leave alone } return this.ajax( url, callback, error ); diff --git a/mobile.html b/mobile.html index c1a14eb..9c07cad 100644 --- a/mobile.html +++ b/mobile.html @@ -55,13 +55,8 @@ // OAuth var client = new forcetk.Client(clientId, loginUrl, proxyUrl);; -// We use $j rather than $ for jQuery -if (window.$j === undefined) { - $j = $; -} - -$j(document).ready(function() { - $j('#login').popupWindow({ +$(document).ready(function() { + $('#login').popupWindow({ windowURL: getAuthorizeUrl(loginUrl, clientId, redirectUri), windowName: 'Connect', centerBrowser: 1, @@ -79,7 +74,6 @@ function sessionCallback(oauthResponse) { if (typeof oauthResponse === 'undefined' || typeof oauthResponse['access_token'] === 'undefined') { - //$j('#prompt').html('Error - unauthorized!'); errorCallback({ status: 0, statusText: 'Unauthorized', @@ -91,10 +85,10 @@ addClickListeners(); - $j.mobile.changePage('#mainpage',"slide",false,true); - $j.mobile.pageLoading(); + $.mobile.changePage('#mainpage',"slide",false,true); + $.mobile.pageLoading(); getAccounts(function(){ - $j.mobile.pageLoading(true); + $.mobile.pageLoading(true); }); } } diff --git a/mobile.page b/mobile.page index 40105bf..c3f54e8 100644 --- a/mobile.page +++ b/mobile.page @@ -50,20 +50,17 @@ an HTML5 mobile app using jQuery Mobile diff --git a/mobileapp.js b/mobileapp.js index 8d7d1b6..f2e8de7 100644 --- a/mobileapp.js +++ b/mobileapp.js @@ -35,85 +35,85 @@ function errorCallback(jqXHR){ } function addClickListeners() { - $j('#newbtn').click(function(e) { + $('#newbtn').click(function(e) { // Show the 'New Account' form e.preventDefault(); - $j('#accountform')[0].reset(); - $j('#accformheader').html('New Account'); + $('#accountform')[0].reset(); + $('#accformheader').text('New Account'); setButtonText('#actionbtn', 'Create'); - $j('#actionbtn').unbind('click.btn').bind('click.btn', createHandler); - $j.mobile.changePage('#editpage', "slide", false, true); + $('#actionbtn').unbind('click.btn').bind('click.btn', createHandler); + $.mobile.changePage('#editpage', "slide", false, true); }); - $j('#deletebtn').click(function(e) { + $('#deletebtn').click(function(e) { // Delete the account e.preventDefault(); - $j.mobile.pageLoading(); - client.del('Account', $j('#accountdetail').find('#Id').val() + $.mobile.pageLoading(); + client.del('Account', $('#accountdetail').find('#Id').val() , function(response) { getAccounts(function() { - $j.mobile.pageLoading(true); - $j.mobile.changePage('#mainpage', "slide", true, true); + $.mobile.pageLoading(true); + $.mobile.changePage('#mainpage', "slide", true, true); }); }, errorCallback); }); - $j('#editbtn').click(function(e) { + $('#editbtn').click(function(e) { // Get account fields and show the 'Edit Account' form e.preventDefault(); - $j.mobile.pageLoading(); - client.retrieve("Account", $j('#accountdetail').find('#Id').val() + $.mobile.pageLoading(); + client.retrieve("Account", $('#accountdetail').find('#Id').val() , "Name,Id,Industry,TickerSymbol", function(response) { - $j('#accountform').find('input').each(function() { - $j(this).val(response[$j(this).attr("name")]); + $('#accountform').find('input').each(function() { + $(this).val(response[$(this).attr("name")]); }); - $j('#accformheader').html('Edit Account'); + $('#accformheader').text('Edit Account'); setButtonText('#actionbtn', 'Update'); - $j('#actionbtn') + $('#actionbtn') .unbind('click.btn') .bind('click.btn', updateHandler); - $j.mobile.pageLoading(true); - $j.mobile.changePage('#editpage', "slide", false, true); + $.mobile.pageLoading(true); + $.mobile.changePage('#editpage', "slide", false, true); }, errorCallback); }); } // Populate the account list and set up click handling function getAccounts(callback) { - $j('#accountlist').empty(); + $('#accountlist').empty(); client.query("SELECT Id, Name FROM Account ORDER BY Name LIMIT 20" , function(response) { - $j.each(response.records, + $.each(response.records, function() { var id = this.Id; - $j('
  • ') + $('
  • ') .hide() .append('

    ' + this.Name + '

    ') .click(function(e) { e.preventDefault(); - $j.mobile.pageLoading(); + $.mobile.pageLoading(); // We could do this more efficiently by adding Industry and // TickerSymbol to the fields in the SELECT, but we want to // show dynamic use of the retrieve function... client.retrieve("Account", id, "Name,Id,Industry,TickerSymbol" , function(response) { - $j('#Name').html(response.Name); - $j('#Industry').html(response.Industry); - $j('#TickerSymbol').html(response.TickerSymbol); - $j('#Id').val(response.Id); - $j.mobile.pageLoading(true); - $j.mobile.changePage('#detailpage', "slide", false, true); + $('#Name').text(response.Name); + $('#Industry').text(response.Industry); + $('#TickerSymbol').text(response.TickerSymbol); + $('#Id').val(response.Id); + $.mobile.pageLoading(true); + $.mobile.changePage('#detailpage', "slide", false, true); }, errorCallback); }) .appendTo('#accountlist') .show(); }); - $j('#accountlist').listview('refresh'); + $('#accountlist').listview('refresh'); if (typeof callback != 'undefined' && callback != null) { callback(); @@ -124,20 +124,20 @@ function getAccounts(callback) { // Gather fields from the account form and create a record function createHandler(e) { e.preventDefault(); - var accountform = $j('#accountform'); + var accountform = $('#accountform'); var fields = {}; accountform.find('input').each(function() { - var child = $j(this); + var child = $(this); if (child.val().length > 0 && child.attr("name") != 'Id') { fields[child.attr("name")] = child.val(); } }); - $j.mobile.pageLoading(); + $.mobile.pageLoading(); client.create('Account', fields, function(response) { getAccounts(function() { - $j.mobile.pageLoading(true); - $j.mobile.changePage('#mainpage', "slide", true, true); + $.mobile.pageLoading(true); + $.mobile.changePage('#mainpage', "slide", true, true); }); }, errorCallback); } @@ -145,21 +145,21 @@ function createHandler(e) { // Gather fields from the account form and update a record function updateHandler(e) { e.preventDefault(); - var accountform = $j('#accountform'); + var accountform = $('#accountform'); var fields = {}; accountform.find('input').each(function() { - var child = $j(this); + var child = $(this); if (child.val().length > 0 && child.attr("name") != 'Id') { fields[child.attr("name")] = child.val(); } }); - $j.mobile.pageLoading(); + $.mobile.pageLoading(); client.update('Account', accountform.find('#Id').val(), fields , function(response) { getAccounts(function() { - $j.mobile.pageLoading(true); - $j.mobile.changePage('#mainpage', "slide", true, true); + $.mobile.pageLoading(true); + $.mobile.changePage('#mainpage', "slide", true, true); }); }, errorCallback); } @@ -167,5 +167,5 @@ function updateHandler(e) { // Ugh - this is required to change text on a jQuery Mobile button // due to the way it futzes with things at runtime function setButtonText(id, str) { - $j(id).html(str).parent().find('.ui-btn-text').text(str); + $(id).text(str).parent().find('.ui-btn-text').text(str); } diff --git a/phonegap.html b/phonegap.html index 1e80547..2f89475 100644 --- a/phonegap.html +++ b/phonegap.html @@ -74,7 +74,7 @@ addClickListeners(); - $j('#logoutbtn').click(function(e) { + $('#logoutbtn').click(function(e) { // Delete the saved refresh token window.plugins.keychain.removeForKey('refresh_token', 'forcetk', @@ -82,8 +82,8 @@ var cb = ChildBrowser.install(); client.setRefreshToken(null); - $j.mobile.changePage('#loginpage', "slide", false, true); - $j.mobile.pageLoading(); + $.mobile.changePage('#loginpage', "slide", false, true); + $.mobile.pageLoading(); cb.onLocationChange = function(loc) { if (loc.startsWith(redirectUri)) { cb.close(); @@ -95,10 +95,10 @@ ); }); - $j.mobile.changePage('#mainpage', "slide", false, true); - $j.mobile.pageLoading(); + $.mobile.changePage('#mainpage', "slide", false, true); + $.mobile.pageLoading(); getAccounts(function() { - $j.mobile.pageLoading(true); + $.mobile.pageLoading(true); }); } @@ -136,18 +136,18 @@ } } - // We use $j rather than $ for jQuery - if (window.$j === undefined) { - $j = $; + // We use $ rather than $ for jQuery + if (window.$ === undefined) { + $ = $; } - $j(document).ready(function() { + $(document).ready(function() { var cb = ChildBrowser.install(); SAiOSKeychainPlugin.install(); window.plugins.keychain.getForKey('refresh_token', 'forcetk', function(key, value) { - $j.mobile.pageLoading(); + $.mobile.pageLoading(); client.setRefreshToken(value); client.refreshAccessToken(sessionCallback, function(jqXHR, textStatus, errorThrown) { From 728e6aa29565b856d5b7cd58c63f6dd5330690af Mon Sep 17 00:00:00 2001 From: Pat Patterson Date: Thu, 15 Jan 2015 21:47:04 -0800 Subject: [PATCH 03/24] jQuery-ized blob sample --- README.markdown | 54 ++++++++++++++++++++++++------------------------- 1 file changed, 27 insertions(+), 27 deletions(-) diff --git a/README.markdown b/README.markdown index b10229f..c29671c 100644 --- a/README.markdown +++ b/README.markdown @@ -22,35 +22,35 @@ Recent Updates * Inserting or updating blob data using the `create` or `update` functions (passing base64-encoded binary data in JSON) is limited by the REST API to 50 MB of text data or 37.5 MB of base64–encoded data. New functions, `createBlob` and `updateBlob`, allow creation and update of ContentVersion and Document records with binary ('blob') content with a size of up to 500 MB. Here is a minimal sample that shows how to upload a file to Chatter Files: - - -

    - Select a file to upload as a new Chatter File. -

    - -

    - + +

    + Select a file to upload as a new Chatter File. +

    + +

    + + +
    - Under the covers, `createBlob` sends a multipart message. See the REST API doc page [Insert or Update Blob Data](https://www.salesforce.com/us/developer/docs/api_rest/Content/dome_sobject_insert_update_blob.htm) for more details. + Under the covers, `createBlob` sends a multipart message. See the REST API doc page [Insert or Update Blob Data](https://www.salesforce.com/us/developer/docs/api_rest/Content/dome_sobject_insert_update_blob.htm) for more details. Dependencies ------------ From 58969932785c2f363d2aa3cb074a3197bd413658 Mon Sep 17 00:00:00 2001 From: Pat Patterson Date: Sun, 8 Mar 2015 21:49:42 -0700 Subject: [PATCH 04/24] First cut of BulkTK --- BulkAPISampleFiles/delete.csv | 5 + BulkAPISampleFiles/delete.xml | 16 +++ BulkAPISampleFiles/insert.csv | 3 + BulkAPISampleFiles/insert.xml | 17 +++ BulkAPISampleFiles/update.csv | 2 + BulkAPISampleFiles/update.xml | 8 ++ BulkAPISampleFiles/upsert.csv | 2 + BulkAPISampleFiles/upsert.xml | 8 ++ BulkTK.md | 121 ++++++++++++++++ bulk.page | 254 ++++++++++++++++++++++++++++++++++ bulktk.js | 239 ++++++++++++++++++++++++++++++++ 11 files changed, 675 insertions(+) create mode 100644 BulkAPISampleFiles/delete.csv create mode 100644 BulkAPISampleFiles/delete.xml create mode 100644 BulkAPISampleFiles/insert.csv create mode 100644 BulkAPISampleFiles/insert.xml create mode 100644 BulkAPISampleFiles/update.csv create mode 100644 BulkAPISampleFiles/update.xml create mode 100644 BulkAPISampleFiles/upsert.csv create mode 100644 BulkAPISampleFiles/upsert.xml create mode 100644 BulkTK.md create mode 100644 bulk.page create mode 100644 bulktk.js diff --git a/BulkAPISampleFiles/delete.csv b/BulkAPISampleFiles/delete.csv new file mode 100644 index 0000000..9535358 --- /dev/null +++ b/BulkAPISampleFiles/delete.csv @@ -0,0 +1,5 @@ +Id +003E000001DJOfxIAH +003E000001DJOfyIAH +003E000001DJOV4IAP +003E000001DJOV5IAP \ No newline at end of file diff --git a/BulkAPISampleFiles/delete.xml b/BulkAPISampleFiles/delete.xml new file mode 100644 index 0000000..e644728 --- /dev/null +++ b/BulkAPISampleFiles/delete.xml @@ -0,0 +1,16 @@ + + + + + 003E000001DJOfxIAH + + + 003E000001DJOfyIAH + + + 003E000001DJOV4IAP + + + 003E000001DJOV5IAP + + \ No newline at end of file diff --git a/BulkAPISampleFiles/insert.csv b/BulkAPISampleFiles/insert.csv new file mode 100644 index 0000000..31cb26a --- /dev/null +++ b/BulkAPISampleFiles/insert.csv @@ -0,0 +1,3 @@ +FirstName,LastName,Department,Birthdate,Description +Tom,Jones,Marketing,1940-06-07Z,"Self-described as ""the top"" branding guru on the West Coast" +Ian,Dury,R&D,,"World-renowned expert in fuzzy logic design. Influential in technology purchases." \ No newline at end of file diff --git a/BulkAPISampleFiles/insert.xml b/BulkAPISampleFiles/insert.xml new file mode 100644 index 0000000..686ed5a --- /dev/null +++ b/BulkAPISampleFiles/insert.xml @@ -0,0 +1,17 @@ + + + + + Tom + Jones + Marketing + 1940-06-07Z + Self-described as "the top" branding guru on the West Coast + + + Ian + Dury + R&D + World-renowned expert in fuzzy logic design. Influential in technology purchases. + + \ No newline at end of file diff --git a/BulkAPISampleFiles/update.csv b/BulkAPISampleFiles/update.csv new file mode 100644 index 0000000..230ef1a --- /dev/null +++ b/BulkAPISampleFiles/update.csv @@ -0,0 +1,2 @@ +Id,Title +003E000001CbzBi,Ninja \ No newline at end of file diff --git a/BulkAPISampleFiles/update.xml b/BulkAPISampleFiles/update.xml new file mode 100644 index 0000000..8574c72 --- /dev/null +++ b/BulkAPISampleFiles/update.xml @@ -0,0 +1,8 @@ + + + + + 003E000001CbzBi + Pirate + + \ No newline at end of file diff --git a/BulkAPISampleFiles/upsert.csv b/BulkAPISampleFiles/upsert.csv new file mode 100644 index 0000000..5841c32 --- /dev/null +++ b/BulkAPISampleFiles/upsert.csv @@ -0,0 +1,2 @@ +Twitter_Handle__c,Title +pattest7,Guru \ No newline at end of file diff --git a/BulkAPISampleFiles/upsert.xml b/BulkAPISampleFiles/upsert.xml new file mode 100644 index 0000000..b942d57 --- /dev/null +++ b/BulkAPISampleFiles/upsert.xml @@ -0,0 +1,8 @@ + + + + + pattest7 + Pirate + + \ No newline at end of file diff --git a/BulkTK.md b/BulkTK.md new file mode 100644 index 0000000..74217e4 --- /dev/null +++ b/BulkTK.md @@ -0,0 +1,121 @@ +BulkTK: Force.com Bulk API JavaScript Toolkit +============================================= + +This minimal toolkit extends ForceTK to allow JavaScript in web pages to call the [Force.com Bulk API](https://www.salesforce.com/us/developer/docs/api_asynch/). + +Background +========== + +The Force.com Bulk API allows asynchronous data access. BulkTK extends ForceTK with methods to create Bulk API jobs, add batches to them, monitor job status and retrieve job results. Control plane XML is parsed to JavaScript objects for ease of use, while data is returned verbatim. + +You should familiarize yourself with the [Force.com Bulk API documentation](https://www.salesforce.com/us/developer/docs/api_asynch/), since BulkTK is a relatively thin layer on the raw XML Bulk API. + +bulk.page is a simple Visualforce single page application to demonstrate BulkTK. Try it out in a sandbox or developer edition. + +Note that, just like ForceTK, BulkTK is unsupported and supplied as is. It is also currently in a very early stage of development. It appears to work well, but bugs cannot be ruled out, and the interface should not be considered stable. + +Example Usage +============= + +You must create a ForceTK client first. On a Visualforce page, you would do: + + var client = new forcetk.Client(); + client.setSessionToken('{!$Api.Session_ID}'); + +See the ForceTK documentation for authenticating from an external website, such as a Heroku app, or PhoneGap/Cordova. + +Create a job +------------ + + // See https://www.salesforce.com/us/developer/docs/api_asynch/Content/asynch_api_reference_jobinfo.htm + // for details of the JobInfo structure + + // Insert Contact records in CSV format + var job = { + operation : 'insert', + object : 'Contact', + contentType : 'CSV' + }; + + client.createJob(job, function(response) { + jobId = response.jobInfo.id; + console.log('Job created with id '+jobId+'\n'); + }, function(jqXHR, textStatus, errorThrown) { + console.log('Error creating job', jqXHR.responseText); + }); + +Add a batch of records to the job +--------------------------------- + +You can add multiple batches to the job; each batch can contain up to 10,000 records. See [batch size and limits](https://www.salesforce.com/us/developer/docs/api_asynch/Content/asynch_api_concepts_limits.htm#batch_size_title) for more details. + + var csvData = "FirstName,LastName,Department,Birthdate,Description\n"+ + "Tom,Jones,Marketing,1940-06-07Z,"Self-described as ""the top"" branding guru on the West Coast\n"+ + "Ian,Dury,R&D,,"World-renowned expert in fuzzy logic design. Influential in technology purchases."\n"; + + client.addBatch(jobId, "text/csv; charset=UTF-8", csvData, + function(response){ + console.log('Added batch '+response.batchInfo.id+'. State: '+response.batchInfo.state+'\n'); + }, function(jqXHR, textStatus, errorThrown) { + console.log('Error adding batch', jqXHR.responseText); + }); + +See BulkAPISampleFiles for sample CSV and XML data for different operations. + +Close the job +------------- + +You must close the job to inform Salesforce that no more batches will be submitted for the job. + + client.closeJob(jobId, function(response){ + console.log('Job closed. State: '+response.jobInfo.state+'\n'); + }, function(jqXHR, textStatus, errorThrown) { + console.log('Error closing job', jqXHR.responseText); + }); + +Check batch status +------------------ + + client.getBatchDetails(jobId, batchId, function(response){ + console.log('Batch state: '+response.batchInfo.state+'\n'); + }, function(jqXHR, textStatus, errorThrown) { + console.log('Error getting batch details', jqXHR.responseText); + }); + +Get batch results +----------------- + +Pass `true` as the `parseXML` parameter to get batch results for a query, false otherwise. + + client.getBatchResult(jobId, batchId, false, function(response){ + console.log('Batch result: '+response); + }, function(jqXHR, textStatus, errorThrown) { + console.log('Error getting batch result', jqXHR.responseText); + }); + +Bulk query +---------- + +When adding a batch to a bulk query job, the `contentType` for the request must be either `text/csv` or `application/xml`, depending on the content type specified when the job was created. The actual SOQL statement supplied for the batch will be in plain text format. + + var soql = 'SELECT Id, FirstName, LastName, Email FROM Contact'; + + client.addBatch(jobId, 'text/csv', soql, function(response){ + console.log('Batch state: '+response.batchInfo.state+'\n'); + }, function(jqXHR, textStatus, errorThrown) { + console.log('Error getting batch result', jqXHR.responseText); + }); + +Getting bulk query results is a two step process. Call `getBatchResult()` with `parseXML` set to `true` to get a set of result IDs, then call `getBulkQueryResult()` to get the actual records for each result + + client.getBatchResult(jobId, batchId, true, function(response){ + response['result-list'].result.forEach(function(resultId){ + client.getBulkQueryResult(jobId, batchId, resultId, function(response){ + console.log('Batch result: '+response); + }, function(jqXHR, textStatus, errorThrown) { + console.log('Error getting bulk query results', jqXHR.responseText); + }); + }); + }, function(jqXHR, textStatus, errorThrown) { + console.log('Error getting batch result', jqXHR.responseText); + }); diff --git a/bulk.page b/bulk.page new file mode 100644 index 0000000..ded3603 --- /dev/null +++ b/bulk.page @@ -0,0 +1,254 @@ + + + + +
    +

    1. Create a Bulk API job


    + + +
    + + +
    + + + +
    +
    +
    
    +    
    + + + + + + + +
    \ No newline at end of file diff --git a/bulktk.js b/bulktk.js new file mode 100644 index 0000000..44c8447 --- /dev/null +++ b/bulktk.js @@ -0,0 +1,239 @@ +/* + * Copyright (c) 2015, salesforce.com, inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided + * that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this list of conditions and the + * following disclaimer. + * + * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and + * the following disclaimer in the documentation and/or other materials provided with the distribution. + * + * Neither the name of salesforce.com, inc. nor the names of its contributors may be used to endorse or + * promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED + * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +/* + * BulkTK: JavaScript library to wrap Force.com Bulk API. Extends ForceTK. + * Dependencies: + * jquery - http://jquery.com/ + * ForceTK - https://github.com/developerforce/Force.com-JavaScript-REST-Toolkit + * jxon - https://github.com/wireload/Ratatosk/blob/master/jxon.js + */ + +forcetk.Client.prototype.xmlHeader = "\n"; + +/* + * Low level utility function to call the Bulk API. + * @param path resource path + * @param parseXML set to true to parse XML response + * @param callback function to which response will be passed + * @param [error=null] function to which jqXHR will be passed in case of error + * @param [method="GET"] HTTP method for call + * @param [contentType=null] Content type of payload - e.g. 'application/xml; charset=UTF-8' + * @param [payload=null] payload for POST + * @param [parseXML=false] set to true to parse XML response + */ +forcetk.Client.prototype.bulkAjax = function(path, parseXML, callback, error, method, contentType, payload, retry) { + var that = this; + var url = this.instanceUrl + path; + + if (this.debug) { + console.log('bulkAjax sending: ', payload); + } + + return $.ajax({ + type: method || "GET", + async: this.asyncAjax, + url: (this.proxyUrl !== null) ? this.proxyUrl: url, + contentType: method == "DELETE" ? null : contentType, + cache: false, + processData: false, + data: payload, + success: function(data, textStatus, jqXHR) { + var respContentType = jqXHR.getResponseHeader('Content-Type'); + // Naughty Bulk API doesn't always set Content-Type! + if (parseXML && + ((respContentType && respContentType.indexOf('application/xml') === 0) || + data.indexOf(' Date: Sun, 8 Mar 2015 21:56:51 -0700 Subject: [PATCH 05/24] More detail in BulkTK readme --- BulkTK.md | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/BulkTK.md b/BulkTK.md index 74217e4..cd07b63 100644 --- a/BulkTK.md +++ b/BulkTK.md @@ -10,19 +10,35 @@ The Force.com Bulk API allows asynchronous data access. BulkTK extends ForceTK w You should familiarize yourself with the [Force.com Bulk API documentation](https://www.salesforce.com/us/developer/docs/api_asynch/), since BulkTK is a relatively thin layer on the raw XML Bulk API. -bulk.page is a simple Visualforce single page application to demonstrate BulkTK. Try it out in a sandbox or developer edition. +[bulk.page](https://github.com/developerforce/Force.com-JavaScript-REST-Toolkit/blob/master/bulk.page) is a simple Visualforce single page application to demonstrate BulkTK. Try it out in a sandbox or developer edition. Note that, just like ForceTK, BulkTK is unsupported and supplied as is. It is also currently in a very early stage of development. It appears to work well, but bugs cannot be ruled out, and the interface should not be considered stable. +Dependencies +============ + + * [jquery](http://jquery.com/) + * [ForceTK](https://github.com/developerforce/Force.com-JavaScript-REST-Toolkit) + * [jxon](https://github.com/wireload/Ratatosk/blob/master/jxon.js) + Example Usage ============= -You must create a ForceTK client first. On a Visualforce page, you would do: +This example focuses on Visualforce. See the [ForceTK documentation](https://github.com/developerforce/Force.com-JavaScript-REST-Toolkit) for details on authenticating from an external website, such as a Heroku app, or PhoneGap/Cordova. + +First, include BulkTK and its dependencies: + + + + + + +Now create a ForceTK client: var client = new forcetk.Client(); client.setSessionToken('{!$Api.Session_ID}'); -See the ForceTK documentation for authenticating from an external website, such as a Heroku app, or PhoneGap/Cordova. +See the [ForceTK documentation](https://github.com/developerforce/Force.com-JavaScript-REST-Toolkit) for details on authenticating from an external website, such as a Heroku app, or PhoneGap/Cordova. Create a job ------------ From 2349e0ae5b5882b511393c82225c5e0c7b218dd6 Mon Sep 17 00:00:00 2001 From: Pat Patterson Date: Mon, 9 Mar 2015 07:11:50 -0700 Subject: [PATCH 06/24] Added jxon.js --- BulkTK.md | 2 +- jxon.js | 140 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 141 insertions(+), 1 deletion(-) create mode 100644 jxon.js diff --git a/BulkTK.md b/BulkTK.md index cd07b63..a5eb38f 100644 --- a/BulkTK.md +++ b/BulkTK.md @@ -19,7 +19,7 @@ Dependencies * [jquery](http://jquery.com/) * [ForceTK](https://github.com/developerforce/Force.com-JavaScript-REST-Toolkit) - * [jxon](https://github.com/wireload/Ratatosk/blob/master/jxon.js) + * [jxon](https://github.com/developerforce/Force.com-JavaScript-REST-Toolkit/blob/master/jxon.js) (originally from the [Ratatosk](https://github.com/wireload/Ratatosk) project; this version preserves case in element and attribute names) Example Usage ============= diff --git a/jxon.js b/jxon.js new file mode 100644 index 0000000..192694d --- /dev/null +++ b/jxon.js @@ -0,0 +1,140 @@ +/* + * JXON.js + * Ratatosk + * + * Created by Alexander Ljungberg on March 15th, 2012. + * + * Public domain JXON implementation from algorithm #3 of: + * https://developer.mozilla.org/en/Parsing_and_serializing_XML + * + * Any copyright is dedicated to the Public Domain. + * + * Modified by Andrew (Pat) Patterson, 2015 from original at + * https://github.com/wireload/Ratatosk/blob/master/jxon.js + * to preserve case of element and attribute names + */ + +JXON = function() +{ + +}; + +JXON.buildValue = function(sValue) +{ + if (/^\s*$/.test(sValue)) + return null; + if (/^(true|false)$/i.test(sValue)) + return sValue.toLowerCase() === "true"; + if (isFinite(sValue)) + return parseFloat(sValue); + // Don't do this - it'll parse anything that looks like a date and get the timezone wrong. + // https://bugzilla.mozilla.org/show_bug.cgi?id=693077 + //if (isFinite(Date.parse(sValue))) + // return new Date(sValue); + return sValue; +}; + +JXON.fromXML = function(xmlString) +{ + return JXON.getJXONData((new DOMParser()).parseFromString(xmlString, "text/xml")); +}; + +JXON.getJXONData = function(oXMLParent) +{ + var vResult = /* put here the default value for empty nodes! */ null, + nLength = 0, + sCollectedTxt = ""; + if (oXMLParent.hasAttributes && oXMLParent.hasAttributes()) + { + vResult = {}; + for (nLength; nLength < oXMLParent.attributes.length; nLength++) + { + oItAttr = oXMLParent.attributes.item(nLength); + vResult["@" + oItAttr.nodeName] = JXON.buildValue(oItAttr.value.replace(/^\s+|\s+$/g, "")); + } + } + if (oXMLParent.hasChildNodes()) + { + for (var oItChild, sItKey, sItVal, nChildId = 0; nChildId < oXMLParent.childNodes.length; nChildId++) + { + oItChild = oXMLParent.childNodes.item(nChildId); + if (oItChild.nodeType === 4) + { + sCollectedTxt += oItChild.nodeValue; + } /* nodeType is "CDATASection" (4) */ + else if (oItChild.nodeType === 3) + { + sCollectedTxt += oItChild.nodeValue.replace(/^\s+|\s+$/g, ""); + } /* nodeType is "Text" (3) */ + else if (oItChild.nodeType === 1 && !oItChild.prefix) + { /* nodeType is "Element" (1) */ + if (nLength === 0) + vResult = {}; + sItKey = oItChild.nodeName; + sItVal = JXON.getJXONData(oItChild); + if (vResult.hasOwnProperty(sItKey)) + { + if (vResult[sItKey].constructor !== Array) + vResult[sItKey] = [vResult[sItKey]]; + vResult[sItKey].push(sItVal); + } + else + { + vResult[sItKey] = sItVal; + nLength++; + } + } + } + } + if (sCollectedTxt) + nLength > 0 ? vResult.keyValue = JXON.buildValue(sCollectedTxt) : vResult = JXON.buildValue(sCollectedTxt); + /* if (nLength > 0) { Object.freeze(vResult); } */ + return vResult; +}; + +JXON.loadObj = function(oParentObj, oParentEl, oNewDoc) +{ + var nSameIdx, + vValue, + oChild; + for (var sName in oParentObj) + { + vValue = oParentObj[sName]; + if (sName === "keyValue") + { + if (vValue !== null && vValue !== true) + oParentEl.appendChild(oNewDoc.createTextNode(String(vValue))); + } + else if (sName.charAt(0) === "@") + oParentEl.setAttribute(sName.slice(1), vValue); + else + { + oChild = oNewDoc.createElement(sName); + if (vValue && vValue.constructor === Date) + oChild.appendChild(oNewDoc.createTextNode(vValue.toGMTString())); + else if (vValue && vValue.constructor === Array) + { + for (nSameIdx = 0; nSameIdx < vValue.length; nSameIdx++) + JXON.loadObj(vValue[nSameIdx], oChild); + } + else if (vValue && vValue instanceof Object) + { + JXON.loadObj(vValue, oChild, oNewDoc); + } + else if (vValue !== null && vValue !== true) + oChild.appendChild(oNewDoc.createTextNode(vValue.toString())); + + oParentEl.appendChild(oChild); + // CPLog.error("Document: " + (new XMLSerializer()).serializeToString(oNewDoc)); + } + } +}; + +JXON.toXML = function(oJXONObj, rootName) +{ + var oNewDoc = document.implementation.createDocument("", "", null), + rootNode = oNewDoc.createElement(rootName || 'xml'); + oNewDoc.appendChild(rootNode); + JXON.loadObj(oJXONObj, rootNode, oNewDoc); + return (new XMLSerializer()).serializeToString(oNewDoc); +}; From c3edd29d3395064db8fc9b402a943f38c3d0333e Mon Sep 17 00:00:00 2001 From: Pat Patterson Date: Mon, 9 Mar 2015 08:26:29 -0700 Subject: [PATCH 07/24] Dependencies, fix proxying in Visualforce --- bulk.page | 1 + bulktk.js | 10 ++++++---- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/bulk.page b/bulk.page index ded3603..e9e7504 100644 --- a/bulk.page +++ b/bulk.page @@ -92,6 +92,7 @@ Sample Visualforce page for Force.com Bulk API JavaScript Toolkit + - - - - - - + + + + + + From 42abd3d633d82b4fc0f97cf5082457cc125422c9 Mon Sep 17 00:00:00 2001 From: Pat Patterson Date: Wed, 1 Apr 2015 08:29:53 -0700 Subject: [PATCH 09/24] Updated jQuery Mobile to latest --- mobileapp.js | 20 ++++++++++---------- phonegap.html | 41 +++++++++++++++++++---------------------- 2 files changed, 29 insertions(+), 32 deletions(-) diff --git a/mobileapp.js b/mobileapp.js index f2e8de7..eeb9242 100644 --- a/mobileapp.js +++ b/mobileapp.js @@ -48,12 +48,12 @@ function addClickListeners() { $('#deletebtn').click(function(e) { // Delete the account e.preventDefault(); - $.mobile.pageLoading(); + $.mobile.loading('show'); client.del('Account', $('#accountdetail').find('#Id').val() , function(response) { getAccounts(function() { - $.mobile.pageLoading(true); + $.mobile.loading('hide'); $.mobile.changePage('#mainpage', "slide", true, true); }); }, errorCallback); @@ -62,7 +62,7 @@ function addClickListeners() { $('#editbtn').click(function(e) { // Get account fields and show the 'Edit Account' form e.preventDefault(); - $.mobile.pageLoading(); + $.mobile.loading('show'); client.retrieve("Account", $('#accountdetail').find('#Id').val() , "Name,Id,Industry,TickerSymbol", function(response) { @@ -74,7 +74,7 @@ function addClickListeners() { $('#actionbtn') .unbind('click.btn') .bind('click.btn', updateHandler); - $.mobile.pageLoading(true); + $.mobile.loading('hide'); $.mobile.changePage('#editpage', "slide", false, true); }, errorCallback); }); @@ -94,7 +94,7 @@ function getAccounts(callback) { .append('

    ' + this.Name + '

    ') .click(function(e) { e.preventDefault(); - $.mobile.pageLoading(); + $.mobile.loading('show'); // We could do this more efficiently by adding Industry and // TickerSymbol to the fields in the SELECT, but we want to // show dynamic use of the retrieve function... @@ -105,7 +105,7 @@ function getAccounts(callback) { $('#Industry').text(response.Industry); $('#TickerSymbol').text(response.TickerSymbol); $('#Id').val(response.Id); - $.mobile.pageLoading(true); + $.mobile.loading('hide'); $.mobile.changePage('#detailpage', "slide", false, true); }, errorCallback); }) @@ -132,11 +132,11 @@ function createHandler(e) { fields[child.attr("name")] = child.val(); } }); - $.mobile.pageLoading(); + $.mobile.loading('show'); client.create('Account', fields, function(response) { getAccounts(function() { - $.mobile.pageLoading(true); + $.mobile.loading('hide'); $.mobile.changePage('#mainpage', "slide", true, true); }); }, errorCallback); @@ -153,12 +153,12 @@ function updateHandler(e) { fields[child.attr("name")] = child.val(); } }); - $.mobile.pageLoading(); + $.mobile.loading('show'); client.update('Account', accountform.find('#Id').val(), fields , function(response) { getAccounts(function() { - $.mobile.pageLoading(true); + $.mobile.loading('hide'); $.mobile.changePage('#mainpage', "slide", true, true); }); }, errorCallback); diff --git a/phonegap.html b/phonegap.html index be7c71f..818d1cd 100644 --- a/phonegap.html +++ b/phonegap.html @@ -48,9 +48,9 @@ from the CDN, but then the device needs to be online for the app to be functional. --> - - - + + + @@ -90,7 +90,7 @@ function() { client.setRefreshToken(null); $.mobile.changePage('#loginpage', "slide", false, true); - $.mobile.pageLoading(); + $.mobile.loading('show'); var ref = window.open(getAuthorizeUrl(loginUrl, clientId, redirectUri), '_blank', 'location=no,toolbar=no'); ref.addEventListener('loadstop', function(evt) { if (evt.url.startsWith(redirectUri)) { @@ -105,9 +105,9 @@ }); $.mobile.changePage('#mainpage', "slide", false, true); - $.mobile.pageLoading(); + $.mobile.loading('show'); getAccounts(function() { - $.mobile.pageLoading(true); + $.mobile.loading('hide'); }); } @@ -152,7 +152,7 @@ keychain = new Keychain(); keychain.getForKey( function(value) { - $.mobile.pageLoading(); + $.mobile.loading('show'); client.setRefreshToken(value); client.refreshAccessToken(sessionCallback, function(jqXHR, textStatus, errorThrown) { @@ -173,7 +173,7 @@ -
    +

    Login

    @@ -184,16 +184,15 @@

    Login

    Force.com

    -
    -
    +
    +

    Account List

    -
      +
      @@ -203,8 +202,8 @@

      Account List

      Force.com

    -
    -
    +
    +

    Account Detail

    @@ -217,15 +216,15 @@

    Account Detail

    + data-theme="b">Delete

    Force.com

    -
    -
    +
    +

    New Account

    @@ -234,17 +233,15 @@

    New Account

    - + - + - +
    Account Name:
    Industry:
    Ticker Symbol:
    From 224c054db9a2c720dbc1c2b800a8fe61ef94776d Mon Sep 17 00:00:00 2001 From: Pat Patterson Date: Wed, 1 Apr 2015 09:52:03 -0700 Subject: [PATCH 10/24] Updated README for Cordova 4.3.0, made sample filename more explicit. --- README.markdown | 109 +++++++++++++++++------------- phonegap.html => cordova-ios.html | 0 2 files changed, 61 insertions(+), 48 deletions(-) rename phonegap.html => cordova-ios.html (100%) diff --git a/README.markdown b/README.markdown index c29671c..2e25be7 100644 --- a/README.markdown +++ b/README.markdown @@ -151,39 +151,50 @@ Your HTML page will need to include jQuery and the toolkit, then create a client More fully featured samples are provided in [example.html](Force.com-JavaScript-REST-Toolkit/blob/master/example.html) and [mobile.html](Force.com-JavaScript-REST-Toolkit/blob/master/mobile.html). -Using the Toolkit in a PhoneGap app ------------------------------------ +Using the Toolkit in a Cordova app +---------------------------------- -Your HTML page will need to include jQuery, the toolkit, PhoneGap and the ChildBrowser plugin, then create a client object, passing a session ID to the constructor. You can use __https://login.salesforce.com/services/oauth2/success__ as the redirect URI and catch the page load in ChildBrowser. +Your HTML page will need to include jQuery, the toolkit and Cordova. You will also need to install the [InAppBrowser](http://plugins.cordova.io/#/package/org.apache.cordova.inappbrowser) plugin to be able to pop up a browser window for authentication. Create a client object, passing a session ID to the constructor. You can use __https://login.salesforce.com/services/oauth2/success__ as the redirect URI and catch the page load in InAppBrowser. An absolutely minimal sample using OAuth to obtain a session ID is: + - - - - - + + + -

    Click here.

    + + + +

    + -A fully featured sample (including persistence of the OAuth refresh token to the iOS Keychain) is provided in [phonegap.html](Force.com-JavaScript-REST-Toolkit/blob/master/phonegap.html). +A fully featured sample (including persistence of the OAuth refresh token to the iOS Keychain) is provided in [cordova-ios.html](Force.com-JavaScript-REST-Toolkit/blob/master/cordova-ios.html). The sample uses Cordova 4.3.0 and the InAppBrowser and iOS Keychain plugins. Install these with + cordova plugin add org.apache.cordova.inappbrowser + cordova plugin add com.shazron.cordova.plugin.keychainutil diff --git a/phonegap.html b/cordova-ios.html similarity index 100% rename from phonegap.html rename to cordova-ios.html From 54e92659d205a7aad41e193be25b22c059995aa2 Mon Sep 17 00:00:00 2001 From: Pat Patterson Date: Wed, 1 Apr 2015 09:58:31 -0700 Subject: [PATCH 11/24] Fixed path to cordova-ios.html --- README.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.markdown b/README.markdown index 2e25be7..e3c0368 100644 --- a/README.markdown +++ b/README.markdown @@ -239,7 +239,7 @@ An absolutely minimal sample using OAuth to obtain a session ID is: -A fully featured sample (including persistence of the OAuth refresh token to the iOS Keychain) is provided in [cordova-ios.html](Force.com-JavaScript-REST-Toolkit/blob/master/cordova-ios.html). The sample uses Cordova 4.3.0 and the InAppBrowser and iOS Keychain plugins. Install these with +A fully featured sample (including persistence of the OAuth refresh token to the iOS Keychain) for iOS is provided in [cordova-ios.html](https://github.com/developerforce/Force.com-JavaScript-REST-Toolkit/blob/master/cordova-ios.html). The sample uses Cordova 4.3.0 and the InAppBrowser and iOS Keychain plugins. Install these with cordova plugin add org.apache.cordova.inappbrowser cordova plugin add com.shazron.cordova.plugin.keychainutil From 0dcaf13e92f3e1bb7f184d81026358f8d8d6cf55 Mon Sep 17 00:00:00 2001 From: Pat Patterson Date: Tue, 26 May 2015 11:25:09 -0700 Subject: [PATCH 12/24] Return null from blob() for async calls - fixes #65 --- forcetk.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/forcetk.js b/forcetk.js index d965d2a..702692e 100644 --- a/forcetk.js +++ b/forcetk.js @@ -323,7 +323,7 @@ if (forcetk.Client === undefined) { request.send(blob); - return this.asyncAjax ? JSON.parse(request.response) : null; + return this.asyncAjax ? null : JSON.parse(request.response); } /* From f177720cc6e67abdbfc9e31ec7c7e05903c881c2 Mon Sep 17 00:00:00 2001 From: Pat Patterson Date: Thu, 28 May 2015 12:06:07 -0700 Subject: [PATCH 13/24] Accept JSON from API --- forcetk.js | 1 + 1 file changed, 1 insertion(+) diff --git a/forcetk.js b/forcetk.js index 702692e..b4deb3e 100644 --- a/forcetk.js +++ b/forcetk.js @@ -293,6 +293,7 @@ if (forcetk.Client === undefined) { var request = new XMLHttpRequest(); request.open("POST", (this.proxyUrl !== null && ! this.visualforce) ? this.proxyUrl: url, this.asyncAjax); + request.setRequestHeader('Accept', 'application/json'); request.setRequestHeader(this.authzHeader, "Bearer " + this.sessionId); request.setRequestHeader('X-User-Agent', 'salesforce-toolkit-rest-javascript/' + this.apiVersion); if (this.proxyUrl !== null && ! this.visualforce) { From b8c759e4a1f43e7fa873efb9a6ac68c4a11d6050 Mon Sep 17 00:00:00 2001 From: Pat Patterson Date: Thu, 28 May 2015 12:07:43 -0700 Subject: [PATCH 14/24] Revert "Accept JSON from API" This reverts commit f177720cc6e67abdbfc9e31ec7c7e05903c881c2. --- forcetk.js | 1 - 1 file changed, 1 deletion(-) diff --git a/forcetk.js b/forcetk.js index b4deb3e..702692e 100644 --- a/forcetk.js +++ b/forcetk.js @@ -293,7 +293,6 @@ if (forcetk.Client === undefined) { var request = new XMLHttpRequest(); request.open("POST", (this.proxyUrl !== null && ! this.visualforce) ? this.proxyUrl: url, this.asyncAjax); - request.setRequestHeader('Accept', 'application/json'); request.setRequestHeader(this.authzHeader, "Bearer " + this.sessionId); request.setRequestHeader('X-User-Agent', 'salesforce-toolkit-rest-javascript/' + this.apiVersion); if (this.proxyUrl !== null && ! this.visualforce) { From fcbb8a784533fa67836d5d8de3298c2e7e06b8ae Mon Sep 17 00:00:00 2001 From: Pat Patterson Date: Thu, 28 May 2015 12:13:26 -0700 Subject: [PATCH 15/24] Accept JSON from API. Fixes #65 --- forcetk.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/forcetk.js b/forcetk.js index 702692e..eef5ac7 100644 --- a/forcetk.js +++ b/forcetk.js @@ -292,7 +292,8 @@ if (forcetk.Client === undefined) { var request = new XMLHttpRequest(); request.open("POST", (this.proxyUrl !== null && ! this.visualforce) ? this.proxyUrl: url, this.asyncAjax); - + + request.setRequestHeader('Accept', 'application/json'); request.setRequestHeader(this.authzHeader, "Bearer " + this.sessionId); request.setRequestHeader('X-User-Agent', 'salesforce-toolkit-rest-javascript/' + this.apiVersion); if (this.proxyUrl !== null && ! this.visualforce) { From 21e7ab9ed0b3ced69316c7ef60e6dac769b2fb9a Mon Sep 17 00:00:00 2001 From: Menno Vanderlist Date: Fri, 10 Jul 2015 09:27:11 -0600 Subject: [PATCH 16/24] Replaced escape(soql) and escape(sosl) Fix to support umlaut and other European charaters Replaced with encodeURIComponent(soql) and encodeURIComponent(sosl) --- forcetk.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/forcetk.js b/forcetk.js index eef5ac7..eb1d7f2 100644 --- a/forcetk.js +++ b/forcetk.js @@ -562,7 +562,7 @@ if (forcetk.Client === undefined) { * @param [error=null] function to which jqXHR will be passed in case of error */ forcetk.Client.prototype.query = function(soql, callback, error) { - return this.ajax('/' + this.apiVersion + '/query?q=' + escape(soql) + return this.ajax('/' + this.apiVersion + '/query?q=' + encodeURIComponent(soql) , callback, error); } @@ -598,7 +598,7 @@ if (forcetk.Client === undefined) { * @param [error=null] function to which jqXHR will be passed in case of error */ forcetk.Client.prototype.search = function(sosl, callback, error) { - return this.ajax('/' + this.apiVersion + '/search?q=' + escape(sosl) + return this.ajax('/' + this.apiVersion + '/search?q=' + encodeURIComponent(sosl) , callback, error); } } From f13596c8aedef867d5aef4978ccf05f275ef948d Mon Sep 17 00:00:00 2001 From: Sean Cuevo Date: Fri, 2 Oct 2015 14:55:29 -0600 Subject: [PATCH 17/24] removing extra new line that would corrupt ms office file attachments --- forcetk.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/forcetk.js b/forcetk.js index eb1d7f2..cc640d7 100644 --- a/forcetk.js +++ b/forcetk.js @@ -286,7 +286,7 @@ if (forcetk.Client === undefined) { + "Content-Disposition: form-data; name=\"" + payloadField + "\"; filename=\"" + filename + "\"\n\n", payload, - "\n\n" + "\n" + "--boundary_" + boundary + "--" ], {type : 'multipart/form-data; boundary=\"boundary_' + boundary + '\"'}); From f05d17c402be989436e42bce16aa5dbaf075f72b Mon Sep 17 00:00:00 2001 From: Sean Cuevo Date: Fri, 2 Oct 2015 14:57:02 -0600 Subject: [PATCH 18/24] adding content type for attachments for IE 11 support --- forcetk.js | 1 + 1 file changed, 1 insertion(+) diff --git a/forcetk.js b/forcetk.js index eb1d7f2..e1865b2 100644 --- a/forcetk.js +++ b/forcetk.js @@ -296,6 +296,7 @@ if (forcetk.Client === undefined) { request.setRequestHeader('Accept', 'application/json'); request.setRequestHeader(this.authzHeader, "Bearer " + this.sessionId); request.setRequestHeader('X-User-Agent', 'salesforce-toolkit-rest-javascript/' + this.apiVersion); + request.setRequestHeader('Content-Type', 'multipart/form-data; boundary=\"boundary_' + boundary + '\"'); if (this.proxyUrl !== null && ! this.visualforce) { request.setRequestHeader('SalesforceProxy-Endpoint', url); } From fb347412c12b482a66e6bccf68a9bf8caad9729c Mon Sep 17 00:00:00 2001 From: Pat Patterson Date: Tue, 6 Oct 2015 11:02:30 -0700 Subject: [PATCH 19/24] Fixed typo in filename parameter. Fixes #74 --- forcetk.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/forcetk.js b/forcetk.js index eef5ac7..ebd6059 100644 --- a/forcetk.js +++ b/forcetk.js @@ -311,7 +311,7 @@ if (forcetk.Client === undefined) { } else if(request.status == 401 && !retry) { that.refreshAccessToken(function(oauthResponse) { that.setSessionToken(oauthResponse.access_token, null,oauthResponse.instance_url); - that.blob(path, fields, fileName, file, callback, error, true); + that.blob(path, fields, filename, file, callback, error, true); }, error); } else { From e12fc025215b5f146f7e5677a2f058c63eeecd61 Mon Sep 17 00:00:00 2001 From: Pat Patterson Date: Wed, 14 Oct 2015 11:25:32 -0700 Subject: [PATCH 20/24] Fixed all JSLint errors/warnings. Fixes #75 --- forcetk.js | 391 ++++++++++++++++++++++++++++------------------------- 1 file changed, 205 insertions(+), 186 deletions(-) diff --git a/forcetk.js b/forcetk.js index 0013562..d568e42 100644 --- a/forcetk.js +++ b/forcetk.js @@ -32,6 +32,9 @@ * console, go to Your Name | Setup | Security Controls | Remote Site Settings */ +/*jslint browser: true*/ +/*global alert, Blob, $, jQuery*/ + var forcetk = window.forcetk; if (forcetk === undefined) { @@ -50,10 +53,11 @@ if (forcetk.Client === undefined) { * PhoneGap etc * @constructor */ - forcetk.Client = function(clientId, loginUrl, proxyUrl) { + forcetk.Client = function (clientId, loginUrl, proxyUrl) { + 'use strict'; this.clientId = clientId; this.loginUrl = loginUrl || 'https://login.salesforce.com/'; - if (typeof proxyUrl === 'undefined' || proxyUrl === null) { + if (proxyUrl === undefined || proxyUrl === null) { if (location.protocol === 'file:' || location.protocol === 'ms-appx:') { // In PhoneGap this.proxyUrl = null; @@ -74,40 +78,42 @@ if (forcetk.Client === undefined) { this.visualforce = false; this.instanceUrl = null; this.asyncAjax = true; - } + }; /** * Set a refresh token in the client. * @param refreshToken an OAuth refresh token */ - forcetk.Client.prototype.setRefreshToken = function(refreshToken) { + forcetk.Client.prototype.setRefreshToken = function (refreshToken) { + 'use strict'; this.refreshToken = refreshToken; - } + }; /** * Refresh the access token. * @param callback function to call on success * @param error function to call on failure */ - forcetk.Client.prototype.refreshAccessToken = function(callback, error) { - var that = this; - var url = this.loginUrl + '/services/oauth2/token'; + forcetk.Client.prototype.refreshAccessToken = function (callback, error) { + 'use strict'; + var that = this, + url = this.loginUrl + '/services/oauth2/token'; return $.ajax({ type: 'POST', - url: (this.proxyUrl !== null && ! this.visualforce) ? this.proxyUrl: url, + url: (this.proxyUrl !== null && !this.visualforce) ? this.proxyUrl : url, cache: false, processData: false, data: 'grant_type=refresh_token&client_id=' + this.clientId + '&refresh_token=' + this.refreshToken, success: callback, error: error, dataType: "json", - beforeSend: function(xhr) { - if (that.proxyUrl !== null && ! this.visualforce) { + beforeSend: function (xhr) { + if (that.proxyUrl !== null && !this.visualforce) { xhr.setRequestHeader('SalesforceProxy-Endpoint', url); } } }); - } + }; /** * Set a session token and the associated metadata in the client. @@ -117,32 +123,32 @@ if (forcetk.Client === undefined) { * @param [instanceUrl] Omit this if running on Visualforce; otherwise * use the value from the OAuth token. */ - forcetk.Client.prototype.setSessionToken = function(sessionId, apiVersion, instanceUrl) { + forcetk.Client.prototype.setSessionToken = function (sessionId, apiVersion, instanceUrl) { + 'use strict'; this.sessionId = sessionId; - this.apiVersion = (typeof apiVersion === 'undefined' || apiVersion === null) - ? 'v29.0': apiVersion; - if (typeof instanceUrl === 'undefined' || instanceUrl == null) { + this.apiVersion = (apiVersion === undefined || apiVersion === null) + ? 'v29.0' : apiVersion; + if (instanceUrl === undefined || instanceUrl === null) { this.visualforce = true; // location.hostname can be of the form 'abc.na1.visual.force.com', // 'na1.salesforce.com' or 'abc.my.salesforce.com' (custom domains). // Split on '.', and take the [1] or [0] element as appropriate - var elements = location.hostname.split("."); - - var instance = null; - if(elements.length == 4 && elements[1] === 'my') { + var elements = location.hostname.split("."), + instance = null; + if (elements.length === 4 && elements[1] === 'my') { instance = elements[0] + '.' + elements[1]; - } else if(elements.length == 3){ + } else if (elements.length === 3) { instance = elements[0]; } else { instance = elements[1]; } - + this.instanceUrl = "https://" + instance + ".salesforce.com"; } else { this.instanceUrl = instanceUrl; } - } + }; /* * Low level utility function to call the Salesforce endpoint. @@ -152,41 +158,42 @@ if (forcetk.Client === undefined) { * @param [method="GET"] HTTP method for call * @param [payload=null] payload for POST/PATCH etc */ - forcetk.Client.prototype.ajax = function(path, callback, error, method, payload, retry) { - var that = this; - var url = (this.visualforce ? '' : this.instanceUrl) + '/services/data' + path; + forcetk.Client.prototype.ajax = function (path, callback, error, method, payload, retry) { + 'use strict'; + var that = this, + url = (this.visualforce ? '' : this.instanceUrl) + '/services/data' + path; return $.ajax({ type: method || "GET", async: this.asyncAjax, - url: (this.proxyUrl !== null && ! this.visualforce) ? this.proxyUrl: url, - contentType: method == "DELETE" ? null : 'application/json', + url: (this.proxyUrl !== null && !this.visualforce) ? this.proxyUrl : url, + contentType: method === "DELETE" ? null : 'application/json', cache: false, processData: false, data: payload, success: callback, - error: (!this.refreshToken || retry ) ? error : function(jqXHR, textStatus, errorThrown) { + error: (!this.refreshToken || retry) ? error : function (jqXHR, textStatus, errorThrown) { if (jqXHR.status === 401) { - that.refreshAccessToken(function(oauthResponse) { + that.refreshAccessToken(function (oauthResponse) { that.setSessionToken(oauthResponse.access_token, null, - oauthResponse.instance_url); + oauthResponse.instance_url); that.ajax(path, callback, error, method, payload, true); }, - error); + error); } else { error(jqXHR, textStatus, errorThrown); } }, dataType: "json", - beforeSend: function(xhr) { - if (that.proxyUrl !== null && ! that.visualforce) { + beforeSend: function (xhr) { + if (that.proxyUrl !== null && !that.visualforce) { xhr.setRequestHeader('SalesforceProxy-Endpoint', url); } xhr.setRequestHeader(that.authzHeader, "Bearer " + that.sessionId); xhr.setRequestHeader('X-User-Agent', 'salesforce-toolkit-rest-javascript/' + that.apiVersion); } }); - } + }; /** * Utility function to query the Chatter API and download a file @@ -200,64 +207,61 @@ if (forcetk.Client === undefined) { * @param [error=null] function to which request will be passed in case of error * @param retry true if we've already tried refresh token flow once */ - forcetk.Client.prototype.getChatterFile = function(path, mimeType, callback, error, retry) { - var that = this; - var url = (this.visualforce ? '' : this.instanceUrl) + path; + forcetk.Client.prototype.getChatterFile = function (path, mimeType, callback, error, retry) { + 'use strict'; + var that = this, + url = (this.visualforce ? '' : this.instanceUrl) + path, + request = new XMLHttpRequest(); - var request = new XMLHttpRequest(); - - request.open("GET", (this.proxyUrl !== null && ! this.visualforce) ? this.proxyUrl: url, true); + request.open("GET", (this.proxyUrl !== null && !this.visualforce) ? this.proxyUrl : url, true); request.responseType = "arraybuffer"; - + request.setRequestHeader(this.authzHeader, "Bearer " + this.sessionId); request.setRequestHeader('X-User-Agent', 'salesforce-toolkit-rest-javascript/' + this.apiVersion); - if (this.proxyUrl !== null && ! this.visualforce) { + if (this.proxyUrl !== null && !this.visualforce) { request.setRequestHeader('SalesforceProxy-Endpoint', url); } - - request.onreadystatechange = function() { + + request.onreadystatechange = function () { // continue if the process is completed - if (request.readyState == 4) { + if (request.readyState === 4) { // continue only if HTTP status is "OK" - if (request.status == 200) { + if (request.status === 200) { try { // retrieve the response callback(request.response); - } - catch(e) { + } catch (e) { // display error message alert("Error reading the response: " + e.toString()); } - } - //refresh token in 401 - else if(request.status == 401 && !retry) { - that.refreshAccessToken(function(oauthResponse) { - that.setSessionToken(oauthResponse.access_token, null,oauthResponse.instance_url); + } else if (request.status === 401 && !retry) { + //refresh token in 401 + that.refreshAccessToken(function (oauthResponse) { + that.setSessionToken(oauthResponse.access_token, null, oauthResponse.instance_url); that.getChatterFile(path, mimeType, callback, error, true); - }, - error); - } - else { + }, error); + } else { // display status message - error(request,request.statusText,request.response); + error(request, request.statusText, request.response); } - } - - } + } + }; request.send(); - - } - + + }; + // Local utility to create a random string for multipart boundary - function randomString() { - var str = ''; - for (var i = 0; i < 4; i++) { - str += (Math.random().toString(16)+"000000000").substr(2,8); + var randomString = function () { + 'use strict'; + var str = '', + i; + for (i = 0; i < 4; i += 1) { + str += (Math.random().toString(16) + "000000000").substr(2, 8); } return str; - } - + }; + /* Low level function to create/update records with blob data * @param path resource path relative to /services/data * @param fields an object containing initial field names and values for @@ -270,63 +274,62 @@ if (forcetk.Client === undefined) { * @param [error=null] function to which response will be passed in case of error * @param retry true if we've already tried refresh token flow once */ - forcetk.Client.prototype.blob = function(path, fields, filename, payloadField, payload, callback, error, retry) { - var that = this; - var url = (this.visualforce ? '' : this.instanceUrl) + '/services/data' + path; - var boundary = randomString(); - - var blob = new Blob([ - "--boundary_" + boundary + '\n' - + "Content-Disposition: form-data; name=\"entity_content\";" + "\n" - + "Content-Type: application/json" + "\n\n" - + JSON.stringify(fields) - + "\n\n" - + "--boundary_" + boundary + "\n" - + "Content-Type: application/octet-stream" + "\n" - + "Content-Disposition: form-data; name=\"" + payloadField - + "\"; filename=\"" + filename + "\"\n\n", - payload, - "\n\n" - + "--boundary_" + boundary + "--" - ], {type : 'multipart/form-data; boundary=\"boundary_' + boundary + '\"'}); - - var request = new XMLHttpRequest(); - request.open("POST", (this.proxyUrl !== null && ! this.visualforce) ? this.proxyUrl: url, this.asyncAjax); + forcetk.Client.prototype.blob = function (path, fields, filename, payloadField, payload, callback, error, retry) { + 'use strict'; + var that = this, + url = (this.visualforce ? '' : this.instanceUrl) + '/services/data' + path, + boundary = randomString(), + blob = new Blob([ + "--boundary_" + boundary + '\n' + + "Content-Disposition: form-data; name=\"entity_content\";" + "\n" + + "Content-Type: application/json" + "\n\n" + + JSON.stringify(fields) + + "\n\n" + + "--boundary_" + boundary + "\n" + + "Content-Type: application/octet-stream" + "\n" + + "Content-Disposition: form-data; name=\"" + payloadField + + "\"; filename=\"" + filename + "\"\n\n", + payload, + "\n\n" + + "--boundary_" + boundary + "--" + ], {type : 'multipart/form-data; boundary=\"boundary_' + boundary + '\"'}), + request = new XMLHttpRequest(); + + request.open("POST", (this.proxyUrl !== null && !this.visualforce) ? this.proxyUrl : url, this.asyncAjax); request.setRequestHeader('Accept', 'application/json'); request.setRequestHeader(this.authzHeader, "Bearer " + this.sessionId); request.setRequestHeader('X-User-Agent', 'salesforce-toolkit-rest-javascript/' + this.apiVersion); - if (this.proxyUrl !== null && ! this.visualforce) { + if (this.proxyUrl !== null && !this.visualforce) { request.setRequestHeader('SalesforceProxy-Endpoint', url); } - + if (this.asyncAjax) { - request.onreadystatechange = function() { + request.onreadystatechange = function () { // continue if the process is completed - if (request.readyState == 4) { + if (request.readyState === 4) { // continue only if HTTP status is good if (request.status >= 200 && request.status < 300) { // retrieve the response callback(request.response ? JSON.parse(request.response) : null); - } else if(request.status == 401 && !retry) { - that.refreshAccessToken(function(oauthResponse) { - that.setSessionToken(oauthResponse.access_token, null,oauthResponse.instance_url); - that.blob(path, fields, filename, file, callback, error, true); - }, - error); + } else if (request.status === 401 && !retry) { + that.refreshAccessToken(function (oauthResponse) { + that.setSessionToken(oauthResponse.access_token, null, oauthResponse.instance_url); + that.blob(path, fields, filename, payloadField, payload, callback, error, true); + }, error); } else { // return status message error(request, request.statusText, request.response); } - } - } + } + }; } - + request.send(blob); - + return this.asyncAjax ? null : JSON.parse(request.response); - } - + }; + /* * Create a record with blob data * @param objtype object type; e.g. "ContentVersion" @@ -340,12 +343,13 @@ if (forcetk.Client === undefined) { * @param [error=null] function to which response will be passed in case of error * @param retry true if we've already tried refresh token flow once */ - forcetk.Client.prototype.createBlob = function(objtype, fields, filename, - payloadField, payload, callback, - error, retry) { - return this.blob('/' + this.apiVersion + '/sobjects/' + objtype + '/', - fields, filename, payloadField, payload, callback, error); - } + forcetk.Client.prototype.createBlob = function (objtype, fields, filename, + payloadField, payload, callback, + error, retry) { + 'use strict'; + return this.blob('/' + this.apiVersion + '/sobjects/' + objtype + '/', + fields, filename, payloadField, payload, callback, error, retry); + }; /* * Update a record with blob data @@ -361,12 +365,13 @@ if (forcetk.Client === undefined) { * @param [error=null] function to which response will be passed in case of error * @param retry true if we've already tried refresh token flow once */ - forcetk.Client.prototype.updateBlob = function(objtype, id, fields, filename, - payloadField, payload, callback, - error, retry) { - return this.blob('/' + this.apiVersion + '/sobjects/' + objtype + '/' + id + - '?_HttpMethod=PATCH', fields, filename, payloadField, payload, callback, error); - } + forcetk.Client.prototype.updateBlob = function (objtype, id, fields, filename, + payloadField, payload, callback, + error, retry) { + 'use strict'; + return this.blob('/' + this.apiVersion + '/sobjects/' + objtype + '/' + id + + '?_HttpMethod=PATCH', fields, filename, payloadField, payload, callback, error, retry); + }; /* * Low level utility function to call the Salesforce endpoint specific for Apex REST API. @@ -378,33 +383,34 @@ if (forcetk.Client === undefined) { * @param [paramMap={}] parameters to send as header values for POST/PATCH etc * @param [retry] specifies whether to retry on error */ - forcetk.Client.prototype.apexrest = function(path, callback, error, method, payload, paramMap, retry) { - var that = this; - var url = this.instanceUrl + '/services/apexrest' + path; + forcetk.Client.prototype.apexrest = function (path, callback, error, method, payload, paramMap, retry) { + 'use strict'; + var that = this, + url = this.instanceUrl + '/services/apexrest' + path; return $.ajax({ type: method || "GET", async: this.asyncAjax, - url: (this.proxyUrl !== null) ? this.proxyUrl: url, + url: (this.proxyUrl !== null) ? this.proxyUrl : url, contentType: 'application/json', cache: false, processData: false, data: payload, success: callback, - error: (!this.refreshToken || retry ) ? error : function(jqXHR, textStatus, errorThrown) { + error: (!this.refreshToken || retry) ? error : function (jqXHR, textStatus, errorThrown) { if (jqXHR.status === 401) { - that.refreshAccessToken(function(oauthResponse) { + that.refreshAccessToken(function (oauthResponse) { that.setSessionToken(oauthResponse.access_token, null, - oauthResponse.instance_url); + oauthResponse.instance_url); that.apexrest(path, callback, error, method, payload, paramMap, true); - }, - error); + }, error); } else { error(jqXHR, textStatus, errorThrown); } }, dataType: "json", - beforeSend: function(xhr) { + beforeSend: function (xhr) { + var paramName; if (that.proxyUrl !== null) { xhr.setRequestHeader('SalesforceProxy-Endpoint', url); } @@ -413,13 +419,15 @@ if (forcetk.Client === undefined) { paramMap = {}; } for (paramName in paramMap) { - xhr.setRequestHeader(paramName, paramMap[paramName]); + if (paramMap.hasOwnProperty(paramName)) { + xhr.setRequestHeader(paramName, paramMap[paramName]); + } } xhr.setRequestHeader(that.authzHeader, "Bearer " + that.sessionId); xhr.setRequestHeader('X-User-Agent', 'salesforce-toolkit-rest-javascript/' + that.apiVersion); } }); - } + }; /* * Lists summary information about each Salesforce.com version currently @@ -428,9 +436,10 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.versions = function(callback, error) { + forcetk.Client.prototype.versions = function (callback, error) { + 'use strict'; return this.ajax('/', callback, error); - } + }; /* * Lists available resources for the client's API version, including @@ -438,9 +447,10 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.resources = function(callback, error) { + forcetk.Client.prototype.resources = function (callback, error) { + 'use strict'; return this.ajax('/' + this.apiVersion + '/', callback, error); - } + }; /* * Lists the available objects and their metadata for your organization's @@ -448,9 +458,10 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.describeGlobal = function(callback, error) { + forcetk.Client.prototype.describeGlobal = function (callback, error) { + 'use strict'; return this.ajax('/' + this.apiVersion + '/sobjects/', callback, error); - } + }; /* * Describes the individual metadata for the specified object. @@ -458,10 +469,11 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.metadata = function(objtype, callback, error) { - return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' - , callback, error); - } + forcetk.Client.prototype.metadata = function (objtype, callback, error) { + 'use strict'; + return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/', + callback, error); + }; /* * Completely describes the individual metadata at all levels for the @@ -470,10 +482,11 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.describe = function(objtype, callback, error) { + forcetk.Client.prototype.describe = function (objtype, callback, error) { + 'use strict'; return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype - + '/describe/', callback, error); - } + + '/describe/', callback, error); + }; /* * Creates a new record of the given type. @@ -484,10 +497,11 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.create = function(objtype, fields, callback, error) { - return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' - , callback, error, "POST", JSON.stringify(fields)); - } + forcetk.Client.prototype.create = function (objtype, fields, callback, error) { + 'use strict'; + return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/', + callback, error, "POST", JSON.stringify(fields)); + }; /* * Retrieves field values for a record of the given type. @@ -498,16 +512,17 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.retrieve = function(objtype, id, fieldlist, callback, error) { - if (arguments.length == 4) { + forcetk.Client.prototype.retrieve = function (objtype, id, fieldlist, callback, error) { + 'use strict'; + if (arguments.length === 4) { error = callback; callback = fieldlist; fieldlist = null; } var fields = fieldlist ? '?fields=' + fieldlist : ''; return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' + id - + fields, callback, error); - } + + fields, callback, error); + }; /* * Upsert - creates or updates record of the given type, based on the @@ -521,10 +536,11 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.upsert = function(objtype, externalIdField, externalId, fields, callback, error) { - return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' + externalIdField + '/' + externalId - + '?_HttpMethod=PATCH', callback, error, "POST", JSON.stringify(fields)); - } + forcetk.Client.prototype.upsert = function (objtype, externalIdField, externalId, fields, callback, error) { + 'use strict'; + return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' + externalIdField + '/' + externalId + + '?_HttpMethod=PATCH', callback, error, "POST", JSON.stringify(fields)); + }; /* * Updates field values on a record of the given type. @@ -536,10 +552,11 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.update = function(objtype, id, fields, callback, error) { - return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' + id - + '?_HttpMethod=PATCH', callback, error, "POST", JSON.stringify(fields)); - } + forcetk.Client.prototype.update = function (objtype, id, fields, callback, error) { + 'use strict'; + return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' + id + + '?_HttpMethod=PATCH', callback, error, "POST", JSON.stringify(fields)); + }; /* * Deletes a record of the given type. Unfortunately, 'delete' is a @@ -549,10 +566,11 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.del = function(objtype, id, callback, error) { - return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' + id - , callback, error, "DELETE"); - } + forcetk.Client.prototype.del = function (objtype, id, callback, error) { + 'use strict'; + return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' + id, + callback, error, "DELETE"); + }; /* * Executes the specified SOQL query. @@ -561,11 +579,12 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.query = function(soql, callback, error) { - return this.ajax('/' + this.apiVersion + '/query?q=' + encodeURIComponent(soql) - , callback, error); - } - + forcetk.Client.prototype.query = function (soql, callback, error) { + 'use strict'; + return this.ajax('/' + this.apiVersion + '/query?q=' + encodeURIComponent(soql), + callback, error); + }; + /* * Queries the next set of records based on pagination. *

    This should be used if performing a query that retrieves more than can be returned @@ -576,19 +595,18 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.queryMore = function( url, callback, error ){ + forcetk.Client.prototype.queryMore = function (url, callback, error) { + 'use strict'; //-- ajax call adds on services/data to the url call, so only send the url after - var serviceData = "services/data"; - var index = url.indexOf( serviceData ); - - if( index > -1 ){ - url = url.substr( index + serviceData.length ); - } else { - //-- leave alone + var serviceData = "services/data", + index = url.indexOf(serviceData); + + if (index > -1) { + url = url.substr(index + serviceData.length); } - - return this.ajax( url, callback, error ); - } + + return this.ajax(url, callback, error); + }; /* * Executes the specified SOSL search. @@ -597,8 +615,9 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.search = function(sosl, callback, error) { - return this.ajax('/' + this.apiVersion + '/search?q=' + encodeURIComponent(sosl) - , callback, error); - } + forcetk.Client.prototype.search = function (sosl, callback, error) { + 'use strict'; + return this.ajax('/' + this.apiVersion + '/search?q=' + encodeURIComponent(sosl), + callback, error); + }; } From 0c736367d2c7569e421df306d7690249214bfdec Mon Sep 17 00:00:00 2001 From: Pat Patterson Date: Mon, 26 Oct 2015 15:29:41 -0700 Subject: [PATCH 21/24] Handle apexrest payloads correctly. Fixes #49 --- forcetk.js | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/forcetk.js b/forcetk.js index 8964464..7fd2918 100644 --- a/forcetk.js +++ b/forcetk.js @@ -380,7 +380,7 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error * @param [method="GET"] HTTP method for call - * @param [payload=null] payload for POST/PATCH etc + * @param [payload=null] string or object with payload for POST/PATCH etc or params for GET * @param [paramMap={}] parameters to send as header values for POST/PATCH etc * @param [retry] specifies whether to retry on error */ @@ -389,10 +389,28 @@ if (forcetk.Client === undefined) { var that = this, url = this.instanceUrl + '/services/apexrest' + path; + method = method || "GET"; + + if (method === "GET") { + // Handle proxied query params correctly + if (this.proxyUrl && payload) { + if (typeof payload !== 'string') { + payload = $.param(payload); + } + url += "?" + payload; + payload = null; + } + } else { + // Allow object payload for POST etc + if (payload && typeof payload !== 'string') { + payload = JSON.stringify(payload); + } + } + return $.ajax({ - type: method || "GET", + type: method, async: this.asyncAjax, - url: (this.proxyUrl !== null) ? this.proxyUrl : url, + url: this.proxyUrl || url, contentType: 'application/json', cache: false, processData: false, From cf2e4e4e33d50a295205d76112b9bbb61b255363 Mon Sep 17 00:00:00 2001 From: svc-scm <48930134+svc-scm@users.noreply.github.com> Date: Tue, 12 Oct 2021 04:05:28 -0700 Subject: [PATCH 22/24] Updated/Added CODEOWNERS with ECCN --- CODEOWNERS | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 CODEOWNERS diff --git a/CODEOWNERS b/CODEOWNERS new file mode 100644 index 0000000..522fa4a --- /dev/null +++ b/CODEOWNERS @@ -0,0 +1,2 @@ +# Comment line immediately above ownership line is reserved for related gus information. Please be careful while editing. +#ECCN:Open Source From 52ab8a54c620a4f5b46257e6ce1a3f6cb6b93efa Mon Sep 17 00:00:00 2001 From: Peter Chittum Date: Fri, 14 Oct 2022 21:06:17 +0100 Subject: [PATCH 23/24] adding oss info files --- CODE_OF_CONDUCT.md | 105 +++++++++++++++++++++++++++++++++++++++++++++ LICENSE.txt | 14 ++++++ SECURITY.md | 7 +++ 3 files changed, 126 insertions(+) create mode 100644 CODE_OF_CONDUCT.md create mode 100644 LICENSE.txt create mode 100644 SECURITY.md diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..b4612a7 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,105 @@ +# Salesforce Open Source Community Code of Conduct + +## About the Code of Conduct + +Equality is a core value at Salesforce. We believe a diverse and inclusive +community fosters innovation and creativity, and are committed to building a +culture where everyone feels included. + +Salesforce open-source projects are committed to providing a friendly, safe, and +welcoming environment for all, regardless of gender identity and expression, +sexual orientation, disability, physical appearance, body size, ethnicity, nationality, +race, age, religion, level of experience, education, socioeconomic status, or +other similar personal characteristics. + +The goal of this code of conduct is to specify a baseline standard of behavior so +that people with different social values and communication styles can work +together effectively, productively, and respectfully in our open source community. +It also establishes a mechanism for reporting issues and resolving conflicts. + +All questions and reports of abusive, harassing, or otherwise unacceptable behavior +in a Salesforce open-source project may be reported by contacting the Salesforce +Open Source Conduct Committee at ossconduct@salesforce.com. + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of gender +identity and expression, sexual orientation, disability, physical appearance, +body size, ethnicity, nationality, race, age, religion, level of experience, education, +socioeconomic status, or other similar personal characteristics. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy toward other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or +advances +* Personal attacks, insulting/derogatory comments, or trolling +* Public or private harassment +* Publishing, or threatening to publish, others' private information—such as +a physical or electronic address—without explicit permission +* Other conduct which could reasonably be considered inappropriate in a +professional setting +* Advocating for or encouraging any of the above behaviors + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned with this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project email +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the Salesforce Open Source Conduct Committee +at ossconduct@salesforce.com. All complaints will be reviewed and investigated +and will result in a response that is deemed necessary and appropriate to the +circumstances. The committee is obligated to maintain confidentiality with +regard to the reporter of an incident. Further details of specific enforcement +policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership and the Salesforce Open Source Conduct +Committee. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][contributor-covenant-home], +version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html. +It includes adaptions and additions from [Go Community Code of Conduct][golang-coc], +[CNCF Code of Conduct][cncf-coc], and [Microsoft Open Source Code of Conduct][microsoft-coc]. + +This Code of Conduct is licensed under the [Creative Commons Attribution 3.0 License][cc-by-3-us]. + +[contributor-covenant-home]: https://www.contributor-covenant.org (https://www.contributor-covenant.org/) +[golang-coc]: https://golang.org/conduct +[cncf-coc]: https://github.com/cncf/foundation/blob/master/code-of-conduct.md +[microsoft-coc]: https://opensource.microsoft.com/codeofconduct/ +[cc-by-3-us]: https://creativecommons.org/licenses/by/3.0/us/ \ No newline at end of file diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..9ba9791 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,14 @@ +BSD 3-Clause License + +Copyright (c) 2022 Salesforce, Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +3. Neither the name of Salesforce.com nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..e31774d --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,7 @@ +## Security + +Please report any security issue to [security@salesforce.com](mailto:security@salesforce.com) +as soon as it is discovered. This library limits its runtime dependencies in +order to reduce the total cost of ownership as much as can be, but all consumers +should remain vigilant and have their security stakeholders review all third-party +products (3PP) like this one and their dependencies. \ No newline at end of file From 01974a1415e6546eb35a7aca9e157b0522d20724 Mon Sep 17 00:00:00 2001 From: Philippe Ozil Date: Wed, 10 Jan 2024 14:10:31 +0100 Subject: [PATCH 24/24] Update README.markdown --- README.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.markdown b/README.markdown index e3c0368..b72c733 100644 --- a/README.markdown +++ b/README.markdown @@ -1,3 +1,7 @@ +> [!WARNING] +> This project is deprecated, use [JSforce](https://jsforce.github.io/) instead. + + Force.com JavaScript REST Toolkit =================================