generated from jairoadi/podium-api-demo-contacts
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
93 lines (81 loc) · 2.18 KB
/
index.js
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
import 'dotenv/config';
import express from 'express';
import fetch from 'node-fetch';
export const app = express();
const baseUrl = 'https://api.podium.com/v4/';
const refreshToken = process.env.REFRESHTOKEN;
const clientID = process.env.CLIENTID;
const clientSecret = process.env.CLIENTSECRET;
app.use(express.urlencoded());
app.use(express.json());
//Retrieve all contacts
app.get('/', async (_req, res) => {
try {
const token = await getTokenID();
if (token) {
const requestAPI = await fetch(`${baseUrl}/contacts`, {
Method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
},
});
const reqResponse = await requestAPI.json();
return res.send(reqResponse);
}
} catch (error) {
console.error('Error', error);
return res.sendStatus(error.response.status);
}
});
//Create a contact for a specified location
app.post('/', async (req, res) => {
try {
const token = await getTokenID();
let request;
if (token) {
request = await fetch(`${baseUrl}/contacts`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
},
body: JSON.stringify(req.body),
});
const reqResponse = await request.json();
return res.send(reqResponse);
} else {
return res.send('No authorization token was found.');
}
} catch (error) {
console.error(error);
return res.send(error);
}
});
export async function getTokenID() {
const bodyData = {
client_id: clientID,
client_secret: clientSecret,
grant_type: 'refresh_token',
refresh_token: refreshToken,
};
try {
const tokenRequest = await fetch(
'https://accounts.podium.com/oauth/token',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(bodyData),
}
);
const tokenResponse = await tokenRequest.json();
if (tokenResponse) {
return tokenResponse.access_token;
}
} catch (error) {
console.error(`Error retrieving a new token, ${error}`);
return error;
}
}