-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
339 lines (297 loc) · 11.9 KB
/
server.js
File metadata and controls
339 lines (297 loc) · 11.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
var jsforce = require('jsforce');
const express = require('express')
var fs = require('fs');
var path = require('path');
const app = express()
app.use(express.json())
//###################################### User CREDENTIAL.################################
//dev edition
let creds = JSON.parse(fs.readFileSync(path.resolve(__dirname, './SF_creds.json')).toString());
//######################################################### User authentification.################################
//###########################################Methode 1 : Users identification once and then initiate connection when http request
const authObject = new jsforce.OAuth2({
loginUrl: creds.instanceURL+'.my.salesforce.com/',//*get from login page */
ClientId : creds.clientID,
clientSecret : creds.clientSecret,
redirectUri : 'http://localhost:1000/myapi/token'
});
//*****************************TESTED BUT PROB IN SCOPE or Redirecting
app.get("/myapi/auth/login", function(req, res) {
// Redirect to Salesforce login/authorization page
console.log("/myapi/auth/login worked, SF redirected me to login page that needs the token route")
res.redirect(authObject.getAuthorizationUrl({scope: 'full'}));//check in app manager
});
//i can access the redirecting url but...
//***************This error is in the auth callback: invalid_client_id: client identifier invalid */
app.get('/myapi/token', (req, res) => {
console.log("inside /token")
const connect = new jsforce.Connection({oauth2: authObject});
connect.login(creds.username, creds.password, function(err, userInfo) {
if (err) { return console.error(err); }
const code = req.query.code;
conn.authorize(code, function(err, userInfo) {
if (err) { return console.error("This error is in the auth callback: " + err); }//******* */
// Now you can get the access token and instance URL information.
console.log('Access Token: ' + conn.accessToken);
console.log('Instance URL: ' + conn.instanceUrl);
console.log('refreshToken: ' + conn.refreshToken);
// logged in user property
console.log('User ID: ' + userInfo.id);
console.log('Org ID: ' + userInfo.organizationId);
// Save them to establish connection next time.
//SF will return some connection information that we will store as session variables to
// use every time we make a new handshake with SF for the calls from each route
req.session.accessToken = conn.accessToken;
req.session.instanceUrl = conn.instanceUrl;
req.session.refreshToken = conn.refreshToken;
//redirect to the login page of SF
res.send("authentification succeded");
});
})
})
//########################################### Methode 2 : Users identification for each request
var conn = new jsforce.Connection({
//loginUrl : 'https://anrpc.my.salesforce.com/'
loginUrl: creds.instanceURL+'.my.salesforce.com/',
ClientId : creds.clientID,
clientSecret : creds.clientSecret,
redirectUri : 'http://localhost:1000/myapi/token'
});
//**************************** task 4 GET ALL ACCOUNTs Request
//SIMPLE QUERY
app.get('/myapi/accounts', (req, res) => {
conn.login(creds.username, creds.password, function(err, userInfo) {
if (err) { return console.error(err); }
let q = 'SELECT id, Site, name FROM account';
conn.query(q, function(err, result1) {
if (err) { return console.error(err); }
res.send(result1)
console.log("all account fetched")
});
}); })
//************************************task 1 GET an account using the ID
app.get('/myapi/account/:accountID', (req, res) => {
conn.login(creds.username, creds.password, function(err, userInfo) {
if (err) { return console.error(err); }
//0018a00001otYcUAAU
conn.sobject("Account").retrieve(req.params.accountID, function(err, account) {
if (err) { return console.error(err); }
console.log("Name : " + account.Name);
})
})
res.send(req.params)
})
//************************************Extra conditional fetch*/
app.get('/myapi/contact/BeforeYestrday', (req,res) => {
conn.login(creds.username, creds.password, function(err, userInfo) {
if (err) { return console.error(err); }
conn.sobject("Contact")
.select('*, Contact.*') // asterisk means all fields in specified level are targeted.
.where("CreatedDate < YESTERDAY") // conditions in raw SOQL where clause.
.execute(function(err, cont) {
for (var i=0; i<cont.length; i++) {
var contact = cont[i];
console.log("Name: " + contact.Name);
}
res.send(cont)
});
})
})
//########################### task 3 update new element request
app.put('/myapi/accounts/:accountID',(req,res)=>{
//in postman
//params: accountID = "0018a00001otYcUAAU"
//body "Last_Name" : "El mhamid"
//body { "Id" : '0018a00001otYcVAAU', "Name" : "canada" }
let account = {
Id : req.body.Id,
Name : req.body.Name
}
conn.login(creds.username, creds.password, function(err, userInfo) {
if (err) { return console.error(err); }
conn.sobject("Account").update(account , function(err, ret) {
if (err || !ret.success) { return console.error(err, ret); }
console.log('Updated Successfully : ' + ret.id);
res.send(ret)
// ...
});
})
})
//************************task 2 : Create a new element
app.post('/myapi/account',(req,res)=>{
/*************in post body
* { "Id" : "0017000000hOMChAAO",
"Name" : "created Account #1" }
*/
const p = req.body
const record = {
Id: p.Id,
Name: p.Name
}
conn.login(creds.username, creds.password, function(err, userInfo) {
if (err) { return console.error(err); }
console.log(record)
// Single record creation
conn.sobject("Account").create(record, function(err, ret) {
if (err || !ret.success) { return console.error(err, ret); }
console.log("Created record id : " + ret.id);
})
});
res.send(record)
})
//*******************************Add multiple records
/*records = [
{ "Id" : "0017000000hOMChAAO", "Name" : "Updated Account #1" },
{ "Id" : "0017000000iKOZTAA4", "Name" : "Updated Account #2" }
]
console.log(records)
conn.sobject("Account").update(records,
function(err, rets) {
if (err) { return console.error(err); }
for (var i=0; i < rets.length; i++) {
if (rets[i].success) {
console.log("Updated Successfully : " + rets[i].id);
}
}
});*/
//********************************TESTED
//CONDITIONAL QUERY
app.get('/myapi/contacts', (req, res) => {
//i am logging eachtime manually and not using the authentif session info
conn.login(creds.username, creds.password, function(err, userInfo) {
if (err) { return console.error(err); }
console.log("SOQL FITCH RESULT")
let q = "SELECT Id, Name, CreatedDate FROM Contact WHERE CreatedDate >= YESTERDAY ORDER BY CreatedDate DESC, Name ASC LIMIT 5 OFFSET 10"
conn.query(q, function(err, result2) {
if (err) { return console.error(err); }
//console.log(result2);
res.send(result2)
});
}); })
// ******************************************task 3 UPDATE Opportunity with parameters
// SET CloseDate = '2013-08-31'
// WHERE Account.Name = 'Salesforce.com'
app.get("myapi/candidate/search/:name", (req,res) => {
conn.login(creds.username, creds.password, function(err, userInfo) {
if (err) { return console.error(err); }
conn.sobject("Account")
.find({ Name: 'canada' }) // "fields" argument is omitted
.execute(function(err, records) {
if (err) { return console.error(err); }
console.log(records);
res.send(records)
});
})
})
//****************************Extra task log in */
app.get('/myapi/',(req,res) =>{
conn.login(creds.username, creds.password, function(err, userInfo) {
if (err) { return console.error(err); }
console.log("User ID: " + userInfo.id);
console.log("Org ID: " + userInfo.organizationId);
console.log("Access token: " + conn.accessToken);
console.log("Instance URL: " + conn.instanceUrl);
res.send(userInfo)
})
})
// ***************************************Extra task to delete an element
//"00001009"
app.delete('/myapi/cases/:caseID', (req,res) => {
conn.login(creds.username, creds.password, function(err, userInfo) {
if (err) { return console.error(err); }
console.log(" inside delete sobject")
conn.sobject('Case')
.find({ CaseNumber : req.params.caseID })
.destroy(function(err, rets) {
if (err) { return console.error(err); }
console.log(rets);
// ...
res.send(rets)
});
})
})
//**************************************Single record deletion
//must delete case with number and opportunity with names
// ***************************************TESTED
/*
app.delete('/myapi/accounts/:accountID', (req,res) => {
//i am logging eachtime manually and not using the authentif session info
conn.login(creds.username, creds.password, function(err, userInfo) {
if (err) { return console.error(err); }
console.log(" inside delete sobject")
conn.sobject("Account").destroy(req.params.accountID, function(err, ret) {
if (err || !ret.success) { return console.error(err, ret); }
console.log('Deleted Successfully : ' + ret.id);
});
})
})
*/
//**************************************Multiple record deletion
/*app.delete('/myapi/accounts', (req,res) => {
conn.login(creds.username, creds.password, function(err, userInfo) {
if (err) { return console.error(err); }
console.log(" inside delete sobject")
conn.sobject("Account").del([ // synonym of "destroy"
'0017000000hOMChAAO',
'0017000000iKOZTAA4'
],
function(err, rets) {
if (err) { return console.error(err); }
for (var i=0; i < rets.length; i++) {
if (rets[i].success) {
console.log("Deleted Successfully : " + rets[i].id);
}
}
});
})
})*/
// ***************************************TESTED
/*
conn.login(creds.username, creds.password, function(err, userInfo) {
if (err) { return console.error(err); }
console.log(" inside delete sobject")
conn.sobject('Opportunity')
.find({ Name : "GenePoint SLA"})
.destroy(function(err, rets) {
if (err) { return console.error(err); }
console.log(rets);
// ...
});
})*/
//***************************************************************************** */
//HTTP REQUESTS
//CRUD
// Multiple record retrieval
/*
//2. Create Records
app.post('/forceapi/records',(req,res)=>{
courses.push(record)
res.send(record)
})*/
/*
conn.login(username, password, function(err, userInfo) {
if (err) { return console.error(err); }
// Now you can get the access token and instance URL information.
// Save them to establish connection next time.
console.log(conn.accessToken);
console.log(conn.instanceUrl);
// logged in user property
console.log("User ID: " + userInfo.id);
console.log("Org ID: " + userInfo.organizationId);
// ...
});*/
/*
var records = [];
conn.query("SELECT Id, Name FROM Account", function(err, result) {
if (err) { return console.error(err); }
console.log("total : " + result.totalSize);
console.log("fetched : " + result.records.length);
});*/
/*conn.query("SELECT Id, Name FROM Account LIMIT 10", function(err, res) {
if (err) { return handleError(err); }
handleResult(res);
});*/
const port = process.env.PORT || 1000
app.listen(port, ()=>{
console.log(`im listening on port ${port}`)
})