-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
632 lines (551 loc) · 22.1 KB
/
index.js
File metadata and controls
632 lines (551 loc) · 22.1 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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
import got from 'got'
import ky from 'ky'
import dayjs from 'dayjs'
import { readPackageSync } from 'read-pkg'
import customParseFormat from 'dayjs/plugin/customParseFormat.js'
dayjs.extend(customParseFormat)
const brandCodes = {
ATWL: 'Atwell Suites',
AVID: 'avid Hotels',
CDLW: 'Candlewood Suites',
HICP: 'Crowne Plaza',
EVEN: 'EVEN Hotels',
HOLI: 'Holiday Inn',
HICV: 'Holiday Inn Club Vacations',
HIEX: 'Holiday Inn Express',
HEXS: 'Holiday Inn Express & Suites',
INDG: 'Hotel Indigo',
HLUX: 'HUALUXE',
ICON: 'InterContinental',
KIKI: 'Kimpton',
MRMS: 'Mr & Mrs Smith',
RGNT: 'Regent',
SIXS: 'Six Senses',
STAY: 'Staybridge Suites',
LXLX: 'Vignette Collection',
VXVX: 'voco'
}
export default class Trippe {
#headers
constructor (apiKey) {
// Check if apiKey was provided
if (!apiKey) {
throw new Error('apiKey is required')
}
// Set headers
const { version } = readPackageSync({
cwd: new URL('./', import.meta.url)
})
this.#headers = {
'x-ihg-api-key': apiKey,
'user-agent': `Trippe/${version}`
}
}
/**
* Gets basic info on a hotel
*
* @param {string} hotelCode The systemwide id (mnemonic) of the hotel
* @returns {Promise<hotelDetails>}
*/
/**
* @typedef {Object} hotelDetails
* @property {string} hotelCode The systemwide id (mnemonic) of the hotel
* @property {string} hotelName The name of the hotel, not taking into account the brand name of the chain it belongs to
* @property {string} brandCode The code of the (sub)chain the hotel belongs to
* @property {string} brandName The brand name of the (sub)chain the hotel belongs to
* @property {hotelDescription} description A description of the property, in two formats
* @property {number} numberOfRooms The number of available rooms
* @property {string} closestCity The closest city to the hotel (may be the actual city of the address)
* @property {Array} street The street part of the property address, with one entry for each line needed (maximum 2)
* @property {string} postalCode The postal code of the property
* @property {string} city The city the hotel is in
* @property {state|null} state The state part of the address, null when not locally used
* @property {string} country The country the hotel is in, expressed as a ISO 3166-1 alpha-2 code
* @property {Array} coordinates The coordinates of the hotel, expressed as [longitude, latitude]
* @property {string} url The url of the hotel's homepage
*/
/**
* @typedef {Object} hotelDescription
* @property {string} long The long description of the property
* @property {string} short The short description of the property
*/
/**
* @typedef {Object} state
* @property {string} code The (local) shorthand used
* @property {string} name The full name
*/
getHotelDetails (hotelCode) {
// Check if hotelCode was provided
if (!hotelCode) {
throw new Error('hotelCode is required')
}
const headers = this.#headers
const url = `https://apis.ihg.com/hotels/v3/profiles/${hotelCode}/details?fieldset=brandInfo,location,profile,address`
return got.get(url, { headers }).json()
.then((json) => json.hotelContent[0])
.then((hotelContent) => {
const { brandInfo, location, profile, address } = hotelContent
const { brandCode } = brandInfo
return {
hotelCode,
hotelName: profile.name.find(({ locale }) => locale === 'en_US').value,
brandCode,
brandName: brandCodes[brandCode],
description: {
long: profile.longDescription.find(({ locale }) => locale === 'en_US').value,
short: profile.shortDescription.find(({ locale }) => locale === 'en_US').value
},
numberOfRooms: profile.roomsIncludingSuitesCount,
closestCity: location.closestCity[0].value,
street: address.translatedMainAddress.line1.find(({ locale }) => locale === 'en_US').value,
postalCode: address.translatedMainAddress.zipcode.find(({ locale }) => locale === 'en_US').value,
city: address.translatedMainAddress.city.find(({ locale }) => locale === 'en_US').value,
state: address.translatedMainAddress.state?.find(({ locale }) => locale === 'en_US').value || null,
country: address.translatedMainAddress.country.find(({ locale }) => locale === 'en_US').value,
coordinates: [+profile.latLong.longitude, +profile.latLong.latitude],
url: address.consumerFriendlyURL ? `https://${address.consumerFriendlyURL}` : null
}
})
.catch((err) => {
console.log(err.code)
throw new Error(err.code === 'ERR_NON_2XX_3XX_RESPONSE' ? 'Unknown or invalid hotelCode' : err)
})
}
/**
* Returns an object with the hotelCode, the currencyCode and an array of lowest prices (in points and in cash) for a
* single hotel - per night and for a period of up to 62 days
* Note that the rates that this method returns don't always include (all) taxes
*
* @param {string} hotelCode The systemwide id of the hotel
* @param {startEndDates} dates An object containing startDate and endDate keys (both optional)
* @returns {Promise<Object[lowestHotelPrices]>}
*/
/**
* @typedef {Object} startEndDates
* @property {string} startDate The date (check in date) from which to start searching, defaults to today
* @property {string} endDate The last date (as a check in date) to include in the search, defaults to today + 61 days
*/
/**
* @typedef { Object } lowestHotelPrices
* @property {string} hotelCode The systemwide id (mnemonic) of the hotel
* @property {string} currencyCode The currency used at this hotel
* @property {lowestPriceDay} prices The lowest prices by day
*/
/**
* @typedef {Object} lowestPriceDay
* @property {string} checkinDate The check in date
* @property {number|null} cashPrice The lowest cash price available - not including (some) taxes for a one night stay, null if no rooms available
* @property {number|null} points The lowest number of points available to book a reward night with points only, null if no reward nights are available
*/
getLowestHotelPrices (hotelCode, {
startDate = dayjs().format('YYYY-MM-DD'),
endDate = dayjs(startDate).add(61, 'day').format('YYYY-MM-DD')
} = {}) {
const headers = this.#headers
// Check if hotelCode was provided
if (!hotelCode) {
throw new Error('hotelCode is required')
}
// Calculate number of days
const days = dayjs(endDate).diff(dayjs(startDate), 'day') + 1
// Check if there's 62 days or less
if (days > 62) {
throw new Error('Please limit the number of days to 62 or less')
}
const url = `https://apis.ihg.com/availability/v1/windows?hotelCodes=${hotelCode.toUpperCase()}&rateCodes=IVANI,IDMAP,IDME0,IDME2,IGCOR,IDVPD,IDMAF&startDate=${startDate}T00:00:00Z&endDate=${endDate}T00:00:00Z&lengthOfStay=1&numberOfRooms=1&includeSellStrategy=never`
return got.get(url, { headers }).json()
.catch((error) => {
const { statusCode } = error.response
if (statusCode >= 500) {
throw new Error(`API reports a server error (statusCode ${statusCode}). Please retry.`)
}
})
.then((json) => json.hotels[0])
.then((hotel) => {
const { currencyCode, rates } = hotel
const dates = [...new Array(days)].map((u, i) => dayjs(startDate).add(i, 'day').format('YYYY-MM-DD'))
if (currencyCode === '') {
throw new Error('Unknown or invalid hotelCode')
} else {
const ratesCombined = rates.flatMap((rate) => rate.windows)
const prices = dates.map((checkinDate) => {
const points = Math.min(...ratesCombined.filter((rate) => rate.startDate === `${checkinDate}T00:00:00Z` && 'totalPoints' in rate).map((rate) => rate.totalPoints))
const cashPrice = Math.min(...ratesCombined.filter((rate) => rate.startDate === `${checkinDate}T00:00:00Z` && 'totalAmount' in rate).map((rate) => rate.totalAmount))
return {
checkinDate,
cashPrice: cashPrice < Infinity ? cashPrice : null,
points: points < Infinity ? points : null
}
})
return {
hotelCode,
currencyCode,
prices
}
}
})
}
/**
* Returns an object with the hotelCode, the currencyCode and an array of lowest cash prices for a
* single hotel - per night and for a period of up to 62 days
* The rates that this method returns should include all taxes
*
* @param {string} hotelCode The systemwide id of the hotel
* @param {startEndDates} dates An object containing startDate and endDate keys (both optional)
* @returns {Promise<Object[lowestHotelPrices]>}
*/
/**
* @typedef {Object} startEndDates
* @property {string} startDate The date (check in date) from which to start searching, defaults to today
* @property {string} endDate The last date (as a check in date) to include in the search, defaults to today + 61 days
*/
/**
* @typedef { Object } lowestHotelPrices
* @property {string} hotelCode The systemwide id (mnemonic) of the hotel
* @property {string} currencyCode The currency used at this hotel
* @property {lowestPriceDay} prices The lowest prices by day
*/
/**
* @typedef {Object} lowestPriceDay
* @property {string} checkinDate The check in date
* @property {number|null} cashPrice The lowest cash price available - not including (some) taxes for a one night stay, null if no rooms available
*/
getLowestHotelCashPrices (hotelCode, {
startDate = dayjs().format('YYYY-MM-DD'),
endDate = dayjs(startDate).add(61, 'day').format('YYYY-MM-DD')
} = {}) {
const headers = this.#headers
// Check if hotelCode was provided...
if (!hotelCode) {
throw new Error('hotelCode is required')
}
// ..and is wellformed
if (!/^[A-Za-z]{5}$/.test(hotelCode)) {
throw new Error('hotelCode is malformed')
}
// Calculate number of days
const days = dayjs(endDate).diff(dayjs(startDate), 'day') + 1
// Check if there's 62 days or less
if (days > 62) {
throw new Error('Please limit the number of days to 62 or less')
}
const url = 'https://apis.ihg.com/availability/v1/calendar'
const json = {
hotelMnemonics: [hotelCode.toUpperCase()],
startDate,
endDate,
lengthOfStay: 1,
rates: {
ratePlanCodes: ['6CBARC']
},
guestCounts: [
{
otaCode: 'AQC10',
count: 1
}
],
options: {
includeSellStrategy: 'followChannel',
returnAmountsAfterTaxForLowestOffer: true,
returnAverages: true,
lowestOfferPerRatePlan: true
}
}
return ky.post(url, { headers, json }).json()
.catch((error) => {
const { status } = error.response
if (status >= 500) {
throw new Error(`API reports a server error (statusCode ${status}). Please retry.`)
}
})
.then((json) => {
if ('warnings' in json) {
throw new Error(`API reports a data error: ${json.warnings[0].message} (Error ${json.warnings[0].code}). Please retry.`)
} else {
return json.data.hotels[0]
}
})
.then((hotelData) => {
const { hotel, calendar } = hotelData
const currencyCode = hotel.propertyCurrency
const dates = [...new Array(days)].map((u, i) => dayjs(startDate).add(i, 'day').format('YYYY-MM-DD'))
return {
hotelCode,
currencyCode,
prices: dates.map((checkinDate) => {
const dayData = calendar.find(({ start }) => start === checkinDate)
return {
checkinDate,
cashPrice: dayData ? dayData.offers.find((d) => 'totalAmountAfterFeeTax' in d).totalAmountAfterFeeTax : null
}
})
}
})
}
/**
* Returns an object containing arrays of available products, available rate plans and available prices
* (in cash and points) for a specific hotel on specific dates
*
* @param {string} hotelCode The systemwide id of the hotel
* @param {startEndDatesAndGuests} options
* @returns {Promise<Object>}
*/
/**
* @typedef {Object} startEndDatesAndGuests
* @property {string} startDate The date (check in date) from which to start searching, defaults to today
* @property {string} endDate The last date (as a check in date) to include in the search, defaults to today + 61 days
* @property {number} adults The number of adult guests in the room
* @property {number} children The number of children in the room
*/
getStayPrices (hotelCode, {
checkinDate = dayjs().format('YYYY-MM-DD'),
checkoutDate = dayjs(checkinDate).add(1, 'day').format('YYYY-MM-DD'),
adults = 1,
children = 0
} = {}) {
const headers = this.#headers
// Check if hotelCode was provided
if (!hotelCode) {
throw new Error('hotelCode is required')
}
// Check checkinDate format
const isValidCheckinDate = dayjs(checkinDate, 'YYYY-MM-DD', true).isValid()
if (!isValidCheckinDate) throw new Error('Invalid value for checkinDate (should be formatted as YYYY-MM-DD)')
const url = 'https://apis.ihg.com/availability/v3/hotels/offers?fieldset=rateDetails,rateDetails.policies,rateDetails.bonusRates,rateDetails.upsells'
const json = {
products: [
{
productCode: 'SR',
guestCounts: [
{
otaCode: 'AQC10',
count: adults
},
{
otaCode: 'AQC8',
count: children
}],
startDate: checkinDate,
endDate: checkoutDate,
quantity: 1
}
],
startDate: checkinDate,
endDate: checkoutDate,
hotelMnemonics: [hotelCode],
rates: {
ratePlanCodes: [
{
internal: 'IVANI'
}
]
},
options: {
disabilityMode: 'ACCESSIBLE_AND_NON_ACCESSIBLE',
returnAdditionalRatePlanDescriptions: true
}
}
return got.post(url, { headers, json, retry: { methods: ['POST'] }, throwHttpErrors: false })
.then((response) => {
if (response.statusCode !== 200) {
const errors = JSON.parse(response.body).errors
if (errors.map((error) => error.code).includes('INVALID_HOTEL_MNEMONICS')) {
throw new Error('Unknown or invalid hotelCode')
} else if (errors.map((error) => error.code).includes('CRS_50010')) {
throw new Error('Unknown or invalid hotelCode')
} else if (errors.map((error) => error.code).includes('CRS_50025')) {
throw new Error('No availabilty for your search')
} else {
throw new Error(errors[0].message)
}
} else {
return JSON.parse(response.body)
}
})
.then((json) => json.hotels[0])
.then((hotelData) => {
// Get list of products offered
const { productDefinitions } = hotelData
const products = productDefinitions
.filter((productDefinition) => 'inventoryTypeName' in productDefinition && productDefinition.isAvailable)
.map((productDefinition) => {
return {
productCode: productDefinition.inventoryTypeCode,
productName: productDefinition.inventoryTypeName,
productDescription: productDefinition.description ? productDefinition.description.trim() : null,
productIsPremium: productDefinition.isPremium
}
})
const currency = hotelData.propertyCurrency
// Get a list of ratePlans offered
const { ratePlanDefinitions } = hotelData
const ratePlans = ratePlanDefinitions
.filter((ratePlanDefinition) => 'additionalDescriptions' in ratePlanDefinition)
.map((ratePlanDefinition) => {
return {
rateCode: ratePlanDefinition.code,
rateName: ratePlanDefinition.additionalDescriptions.longRateName,
rateDescription: ratePlanDefinition.additionalDescriptions.longRateDesc
}
})
// Check rates per room type
const { rateDetails } = hotelData
const prices = rateDetails.offers.map((offer) => {
const productCode = offer.productUses[0].inventoryTypeCode
const rateCode = offer.ratePlanCode
const cashPrice = 'rewardNights' in offer ? null : parseFloat(offer.productUses[0].rates.totalRate.average.amountAfterTax)
let points = null
if ('rewardNights' in offer) {
const noCash = {
points: offer.rewardNights.pointsOnly.averageDailyPoints,
cashPrice: 0
}
const cashOptions = 'options' in offer.rewardNights.pointsCash
? offer.rewardNights.pointsCash.options.map((option) => {
return {
points: option.averageDailyPoints,
cashPrice: option.averageDailyCash
}
})
: []
points = [noCash, ...cashOptions]
}
return {
productCode,
rateCode,
cashPrice,
points
}
})
return {
products,
ratePlans,
currency,
prices: prices.sort((a, b) => a.ratePrice < b.ratePrice ? -1 : 1)
}
})
}
/**
* Returns an array of lowest prices (in points and in cash) in a search area and for a given night
*
* @param {string} centrePoint The point (in [longitude, latitude] notation) to search from
* @param {object} options An object containing radius, unit and checkinDate parameters (all optional)
* @returns {Promise<Array>}
*/
getLowestAreaPrices (coordinates, {
radius = 100,
unit = 'mi',
checkinDate = dayjs().format('YYYY-MM-DD'),
adults = 1,
children = 0
} = {}) {
const headers = this.#headers
const url = 'https://apis.ihg.com/availability/v3/hotels/offers?fieldset=summary,summary.rateRanges'
// Check coordinates
const validCoordinates = Array.isArray(coordinates) && coordinates.length === 2 && coordinates.every((d) => typeof (d) === 'number')
if (!validCoordinates) throw new Error('Invalid format used for coordinates, please use [lng, lat]')
const [longitude, latitude] = coordinates
// Check checkinDate format
const isValidCheckinDate = dayjs(checkinDate, 'YYYY-MM-DD', true).isValid()
if (!isValidCheckinDate) throw new Error('Invalid value for checkinDate (should be formatted as YYYY-MM-DD)')
const checkoutDate = dayjs(checkinDate).add(1, 'day').format('YYYY-MM-DD')
// Check distance unit
if (!['KM', 'MI'].includes(unit.toUpperCase())) throw new Error('Wrong distance unit provided')
// Check maximum distance
if (radius > 100) throw new Error('The value of radius should not be greater than 100')
const json = {
products: [
{
productCode: 'SR',
guestCounts: [
{
otaCode: 'AQC10',
count: adults
},
{
otaCode: 'AQC8',
count: children
}
],
quantity: 1
}
],
radius,
distanceUnit: unit.toUpperCase(),
distanceType: 'STRAIGHT_LINE',
startDate: checkinDate,
endDate: checkoutDate,
geoLocation: [
{
longitude,
latitude
}
],
rates: {
ratePlanCodes: [
{
internal: 'IVANI'
}
]
}
}
return got.post(url, { headers, json, retry: { methods: ['POST'] } }).json()
.then((json) => json.hotels)
.then((hotels) => hotels.filter((hotel) => hotel.availabilityStatus === 'OPEN'))
.then((hotels) => hotels.map((hotel) => {
const { hotelMnemonic: hotelCode, propertyCurrency: currencyCode, lowestPointsOnlyCost, lowestCashOnlyCost } = hotel
const cashPrice = parseFloat(lowestCashOnlyCost.amountAfterTax)
const points = lowestPointsOnlyCost ? lowestPointsOnlyCost.points : null
return {
hotelCode,
cashPrice,
currencyCode,
points
}
}))
}
/**
* Returns a list of destinations and their coordinates
*
* @param {string} query A query to autocomplete, at least 3 characters long
* @returns {Promise<Array>}
*/
getDestinations (query) {
// Check that the query is 3 characters or longer
if (query.length < 3) throw new Error('Query string should be 3 characters or more')
const headers = this.#headers
const url = `https://apis.ihg.com/locations/v1/destinations?destination=${query}`
return got.get(url, { headers }).json()
.then((locations) => {
return locations.map((location) => {
const { longitude, latitude, clarifiedLocation: display } = location
return {
coordinates: [longitude, latitude],
display
}
})
})
}
/**
* Returns a url that will show the room and rate options for the given hotel
* with the givebn check in and check out dates
*
* @param {string} hotelCode The systemwide id of the hotel
* @param {object} dates An object containing startDate and endDate keys (both optional)
* @returns {Promise<Array>}
*/
getBookingPageUrl (hotelCode, {
checkinDate = dayjs().format('YYYY-MM-DD'),
checkoutDate = dayjs(checkinDate).add(1, 'day').format('YYYY-MM-DD'),
adults = 1,
children = 0
} = {}) {
const checkinDateElements = checkinDate.split('-')
const checkinDay = checkinDateElements[2]
const checkinMonthYear = `${(+checkinDateElements[1] - 1).toString().padStart(2, '0')}${checkinDateElements[0]}`
const checkoutDateElements = checkoutDate.split('-')
const checkoutDay = checkoutDateElements[2]
const checkoutMonthYear = `${(+checkoutDateElements[1] - 1).toString().padStart(2, '0')}${checkoutDateElements[0]}`
return `https://www.ihg.com/hotels/gb/en/find-hotels/select-roomrate?qDest=%20&qSlH=${hotelCode}&qRms=1&qAdlt=${adults}&qChld=${children}&qCiD=${checkinDay}&qCiMy=${checkinMonthYear}&qCoD=${checkoutDay}&qCoMy=${checkoutMonthYear}`
}
}