-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
208 lines (208 loc) · 7.6 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
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
import Debug from 'debug';
import { objectToUrlSearchParameters } from './utilities.js';
const debug = Debug('avanti-api');
export const _defaultLatestASSP = false;
export class AvantiApi {
#apiConfiguration;
#accessTokenUrl;
#accessTokenTimeMillis = 0;
#accessToken;
constructor(configuration) {
this.#apiConfiguration = configuration;
this.#accessTokenUrl =
(this.#apiConfiguration.latestASSP ?? _defaultLatestASSP)
? 'https://auth.myavanti.ca/connect/token'
: `https://myavanti.ca/${this.#apiConfiguration.tenant}-api/connect/token`;
}
#getEndpointUrl(apiEndpoint) {
return (this.#apiConfiguration.latestASSP ?? _defaultLatestASSP)
? `https://${this.#apiConfiguration.tenant}.myavanti.ca/api${apiEndpoint}`
: `https://myavanti.ca/${this.#apiConfiguration.tenant}-api${apiEndpoint}`;
}
async #refreshAccessToken() {
this.#accessTokenTimeMillis = Date.now();
const requestObject = Object.assign({
grant_type: 'password',
device_id: this.#apiConfiguration.device_id ??
`node-avanti-api-${Date.now().toString()}`
}, {
client_id: this.#apiConfiguration.client_id,
client_secret: this.#apiConfiguration.client_secret,
username: this.#apiConfiguration.username,
password: this.#apiConfiguration.password,
company: this.#apiConfiguration.company
});
const request = objectToUrlSearchParameters(requestObject);
debug(`Access token request: ${this.#accessTokenUrl}`);
const response = await fetch(this.#accessTokenUrl, {
method: 'post',
headers: {
Accept: 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
'x-tenant': this.#apiConfiguration.tenant
},
body: request
});
this.#accessToken = (await response.json());
if ((this.#accessToken?.access_token ?? '') === '') {
debug('Error retrieving access token.');
}
return this.#accessToken;
}
/**
* Requests an API endpoint excluded from the included functions.
* @param apiEndpoint - ex. '/v1/Employees'
* @param apiOptions - API Options
* @returns API Response
*/
async callApi(apiEndpoint, apiOptions) {
// eslint-disable-next-line @typescript-eslint/naming-convention
let access_token = this.#accessToken?.access_token ?? '';
if (access_token === '' ||
this.#accessTokenTimeMillis + (this.#accessToken?.expires_in ?? 0) <=
Date.now()) {
const accessTokenResponse = await this.#refreshAccessToken();
access_token = accessTokenResponse.access_token;
}
let requestUrl = this.#getEndpointUrl(apiEndpoint);
debug(`API request: ${requestUrl}`);
if (apiOptions.method === 'get') {
requestUrl += `?${objectToUrlSearchParameters(apiOptions.getParameters ?? {}).toString()}`;
}
const fetchOptions = {
method: apiOptions.method,
headers: {
Authorization: `Bearer ${access_token}`
}
};
if (apiOptions.method === 'post') {
fetchOptions.body = JSON.stringify(apiOptions.bodyParameters);
fetchOptions.headers['Content-Type'] =
'application/json';
}
const response = await fetch(requestUrl, fetchOptions);
// eslint-disable-next-line @typescript-eslint/init-declarations
let parsingError;
try {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const json = (await response.json()) ?? {};
if (typeof json === 'object' &&
(Object.hasOwn(json, 'status') ||
Object.hasOwn(json, 'instance'))) {
return {
success: false,
error: json
};
}
return {
success: true,
response: json
};
}
catch (error) {
parsingError = error;
}
return {
success: false,
error: {
title: 'callApi() error',
status: 600,
detail: parsingError === undefined ? undefined : parsingError.name,
error: parsingError,
instance: apiEndpoint
}
};
}
/**
* List Employees:
* /v1/Employees
* @param parameters - Request parameters
* @returns See https://avanti.stoplight.io/docs/avanti-api/62932b8f232fb-list-employees
*/
async getEmployees(parameters) {
return (await this.callApi('/v1/Employees', {
method: 'post',
bodyParameters: parameters
}));
}
/**
* List Employee Earning Codes:
* /v1/EmployeeEarningCodes
* @param employeeNumber - Employee number
* @returns See https://avanti.stoplight.io/docs/avanti-api/204d3078d2230-list-employee-earning-codes
*/
async getEmployeeEarningCodes(employeeNumber) {
return (await this.callApi('/v1/EmployeeEarningCodes', {
method: 'get',
getParameters: {
empNo: employeeNumber
}
}));
}
/**
* Get Employee Job Data:
* /v1/EmployeeJobData
* @param employeeNumber - Employee number
* @returns See https://avanti.stoplight.io/docs/avanti-api/a44b4af6f1abd-get-employee-job-data
*/
async getEmployeeJobData(employeeNumber) {
return (await this.callApi('/v1/EmployeeJobData', {
method: 'get',
getParameters: {
empNo: employeeNumber
}
}));
}
/**
* Get Employee Personal Info:
* /v1/PersonalInfo
* @param employeeNumber - Employee number
* @returns See https://avanti.stoplight.io/docs/avanti-api/f851b988b5cf6-get-employee-personal-info
*/
async getEmployeePersonalInfo(employeeNumber) {
return (await this.callApi('/v1/PersonalInfo', {
method: 'get',
getParameters: {
empNo: employeeNumber
}
}));
}
/**
* List Time Entries:
* /v1/TimeManagement/{viewId}/{templateId}
* @param viewId - View Id
* @param templateId - Template Id
* @param parameters - Request parameters
* @returns See https://avanti.stoplight.io/docs/avanti-api/4952dd2917595-list-time-entries
*/
async getTimeEntries(viewId, templateId, parameters) {
return (await this.callApi(`/v1/TimeManagement/${viewId}/${templateId}`, {
method: 'get',
getParameters: parameters
}));
}
/**
* List Time Entry Templates:
* /v1/TimeManagement/Templates
* @param parameters - Request parameters
* @returns See https://avanti.stoplight.io/docs/avanti-api/faa0ddb0eb18d-list-time-entry-templates
*/
async getTimeEntryTemplates(parameters) {
return (await this.callApi('/v1/TimeManagement/Templates', {
method: 'get',
getParameters: parameters
}));
}
/**
* Get Report Data:
* /v1/Reporter/{reportId}
* @param reportId - The ID of the report you would like to get the data for.
* @returns See https://avanti.stoplight.io/docs/avanti-api/ed0485a9c98bb-get-report-data
*/
async getReport(reportId) {
return (await this.callApi(`/v1/Reporter/${reportId}`, {
method: 'get'
}));
}
}
export * as lookups from './lookups.js';