All files / src serverApiClient.ts

88.33% Statements 53/60
57.14% Branches 12/21
88.88% Functions 8/9
88.33% Lines 53/60

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 3568x 8x                       8x 8x   8x                 8x               7x       7x 7x 7x 7x                                                 9x       9x               9x   9x         9x   8x 3x     5x                                                                                   8x       8x       8x             8x   8x           8x 1x     7x   6x                                                                   8x       8x               8x   8x         8x 1x     7x   6x                                                                                         10x       10x               10x   10x         10x   9x 6x     3x                                                                   7x             7x   7x         7x   6x 1x     5x       42x       42x      
import { getRequestPath } from './urlUtils'
import {
  AuthenticationMode,
  EventResponse,
  EventsUpdateRequest,
  FingerprintApi,
  Options,
  Region,
  RelatedVisitorsFilter,
  RelatedVisitorsResponse,
  VisitorHistoryFilter,
  VisitorsResponse,
} from './types'
import { copyResponseJson } from './responseUtils'
import { handleErrorResponse } from './errors/handleErrorResponse'
 
export class FingerprintJsServerApiClient implements FingerprintApi {
  public readonly region: Region
 
  public readonly apiKey: string
 
  public readonly authenticationMode: AuthenticationMode
 
  protected readonly fetch: typeof fetch
 
  protected static readonly DEFAULT_RETRY_AFTER = 1
 
  /**
   * FingerprintJS server API client used to fetch data from FingerprintJS
   * @constructor
   * @param {Options} options - Options for FingerprintJS server API client
   */
  constructor(options: Readonly<Options>) {
    Iif (!options.apiKey) {
      throw Error('Api key is not set')
    }
 
    this.region = options.region ?? Region.Global
    this.apiKey = options.apiKey
    this.authenticationMode = options.authenticationMode ?? AuthenticationMode.AuthHeader // Default auth mode is AuthHeader
    this.fetch = options.fetch ?? fetch
  }
 
  /**
   * Retrieves a specific identification event with the information from each activated product — Identification and all active [Smart signals](https://dev.fingerprint.com/docs/smart-signals-overview).
   *
   * @param requestId - identifier of the event
   *
   * @returns {Promise<EventResponse>} - promise with event response. For more information, see the [Server API documentation](https://dev.fingerprint.com/reference/getevent).
   *
   * @example
   * ```javascript
   * client
   *  .getEvent('<requestId>')
   *  .then((result) => console.log(result))
   *  .catch((error) => {
   *    if (error instanceof RequestError) {
   *       console.log(error.statusCode, error.message)
   *       // Access raw response in error
   *       console.log(error.response)
   *     }
   *   })
   * ```
   * */
  public async getEvent(requestId: string): Promise<EventResponse> {
    Iif (!requestId) {
      throw new TypeError('requestId is not set')
    }
 
    const url = getRequestPath({
      path: '/events/{request_id}',
      region: this.region,
      apiKey: this.getQueryApiKey(),
      pathParams: [requestId],
      method: 'get',
    })
 
    const headers = this.getHeaders()
 
    const response = await this.fetch(url, {
      method: 'GET',
      headers,
    })
 
    const jsonResponse = await copyResponseJson(response)
 
    if (response.status === 200) {
      return jsonResponse as EventResponse
    }
 
    handleErrorResponse(jsonResponse, response)
  }
 
  /**
   * Update an event with a given request ID
   * @description Change information in existing events specified by `requestId` or *flag suspicious events*.
   *
   * When an event is created, it is assigned `linkedId` and `tag` submitted through the JS agent parameters. This information might not be available on the client so the Server API allows for updating the attributes after the fact.
   *
   * **Warning** It's not possible to update events older than 10 days.
   *
   * @param body - Data to update the event with.
   * @param requestId The unique event [identifier](https://dev.fingerprint.com/docs/js-agent#requestid).
   *
   * @return {Promise<void>}
   *
   * @example
   * ```javascript
   * const body = {
   *  linkedId: 'linked_id',
   *  suspect: false,
   * }
   *
   * client
   *   .updateEvent(body, '<requestId>')
   *   .then(() => {
   *     // Event was successfully updated
   *   })
   *  .catch((error) => {
   *    if (error instanceof RequestError) {
   *       console.log(error.statusCode, error.message)
   *       // Access raw response in error
   *       console.log(error.response)
   *
   *       if(error.statusCode === 409) {
   *          // Event is not mutable yet, wait a couple of seconds and retry the update.
   *       }
   *     }
   *   })
   * ```
   */
  public async updateEvent(body: EventsUpdateRequest, requestId: string): Promise<void> {
    Iif (!body) {
      throw new TypeError('body is not set')
    }
 
    Iif (!requestId) {
      throw new TypeError('requestId is not set')
    }
 
    const url = getRequestPath({
      path: '/events/{request_id}',
      region: this.region,
      apiKey: this.getQueryApiKey(),
      pathParams: [requestId],
      method: 'put',
    })
    const headers = this.getHeaders()
 
    const response = await this.fetch(url, {
      method: 'PUT',
      headers,
      body: JSON.stringify(body),
    })
 
    if (response.status === 200) {
      return
    }
 
    const jsonResponse = await copyResponseJson(response)
 
    handleErrorResponse(jsonResponse, response)
  }
 
  /**
   * Delete data by visitor ID
   * Request deleting all data associated with the specified visitor ID. This API is useful for compliance with privacy regulations. All delete requests are queued:
   * Recent data (10 days or newer) belonging to the specified visitor will be deleted within 24 hours. * Data from older (11 days or more) identification events  will be deleted after 90 days.
   * If you are interested in using this API, please [contact our support team](https://fingerprint.com/support/) to activate it for you. Otherwise, you will receive a 403.
   *
   * @param visitorId The [visitor ID](https://dev.fingerprint.com/docs/js-agent#visitorid) you want to delete.*
   *
   * @return {Promise<void>} Promise that resolves when the deletion request is successfully queued
   *
   * @example
   * ```javascript
   * client
   *   .deleteVisitorData('<visitorId>')
   *   .then(() => {
   *     // Data deletion request was successfully queued
   *   })
   *  .catch((error) => {
   *    if (error instanceof RequestError) {
   *       console.log(error.statusCode, error.message)
   *       // Access raw response in error
   *       console.log(error.response)
   *
   *       if(error instanceof TooManyRequestsError) {
   *          retryLater(error.retryAfter) // Needs to be implemented on your side
   *       }
   *     }
   *   })
   * ```
   */
  public async deleteVisitorData(visitorId: string): Promise<void> {
    Iif (!visitorId) {
      throw TypeError('VisitorId is not set')
    }
 
    const url = getRequestPath({
      path: '/visitors/{visitor_id}',
      region: this.region,
      apiKey: this.getQueryApiKey(),
      pathParams: [visitorId],
      method: 'delete',
    })
 
    const headers = this.getHeaders()
 
    const response = await this.fetch(url, {
      method: 'DELETE',
      headers,
    })
 
    if (response.status === 200) {
      return
    }
 
    const jsonResponse = await copyResponseJson(response)
 
    handleErrorResponse(jsonResponse, response)
  }
 
  /**
   * @deprecated Please use {@link FingerprintJsServerApiClient.getVisits} instead
   * */
  public async getVisitorHistory(visitorId: string, filter?: VisitorHistoryFilter): Promise<VisitorsResponse> {
    return this.getVisits(visitorId, filter)
  }
 
  /**
   * Retrieves event history for the specific visitor using the given filter, returns a promise with visitor history response.
   *
   * @param {string} visitorId - Identifier of the visitor
   * @param {VisitorHistoryFilter} filter - Visitor history filter
   * @param {string} filter.limit - limit scanned results
   * @param {string} filter.request_id - filter visits by `requestId`.
   * @param {string} filter.linked_id - filter visits by your custom identifier.
   * @param {string} filter.paginationKey - use `paginationKey` to get the next page of results.   When more results are available (e.g., you requested 200 results using `limit` parameter, but a total of 600 results are available), the `paginationKey` top-level attribute is added to the response. The key corresponds to the `requestId` of the last returned event. In the following request, use that value in the `paginationKey` parameter to get the next page of results:
   *
   *   1. First request, returning most recent 200 events: `GET api-base-url/visitors/:visitorId?limit=200`
   *   2. Use `response.paginationKey` to get the next page of results: `GET api-base-url/visitors/:visitorId?limit=200&paginationKey=1683900801733.Ogvu1j`
   *
   *   Pagination happens during scanning and before filtering, so you can get less visits than the `limit` you specified with more available on the next page. When there are no more results available for scanning, the `paginationKey` attribute is not returned.
   * @example
   * ```javascript
   * client
   *   .getVisits('<visitorId>', { limit: 1 })
   *   .then((visitorHistory) => {
   *     console.log(visitorHistory)
   *   })
   *   .catch((error) => {
   *    if (error instanceof RequestError) {
   *       console.log(error.statusCode, error.message)
   *       // Access raw response in error
   *       console.log(error.response)
   *
   *       if(error instanceof TooManyRequestsError) {
   *          retryLater(error.retryAfter) // Needs to be implemented on your side
   *       }
   *     }
   *   })
   * ```
   */
  public async getVisits(visitorId: string, filter?: VisitorHistoryFilter): Promise<VisitorsResponse> {
    Iif (!visitorId) {
      throw TypeError('VisitorId is not set')
    }
 
    const url = getRequestPath({
      path: '/visitors/{visitor_id}',
      region: this.region,
      apiKey: this.getQueryApiKey(),
      pathParams: [visitorId],
      method: 'get',
      queryParams: filter,
    })
    const headers = this.getHeaders()
 
    const response = await this.fetch(url, {
      method: 'GET',
      headers,
    })
 
    const jsonResponse = await copyResponseJson(response)
 
    if (response.status === 200) {
      return jsonResponse as VisitorsResponse
    }
 
    handleErrorResponse(jsonResponse, response)
  }
 
  /**
   * Related visitors API lets you link web visits and in-app browser visits that originated from the same mobile device.
   * It searches the past 6 months of identification events to find the visitor IDs that belong to the same mobile device as the given visitor ID.
   * ⚠️ Please note that this API is not enabled by default and is billable separately. ⚠️
   * If you would like to use Related visitors API, please contact our [support team](https://fingerprint.com/support).
   * To learn more, see [Related visitors API reference](https://dev.fingerprint.com/reference/related-visitors-api).
   *
   * @param {RelatedVisitorsFilter} filter - Related visitors filter
   * @param {string} filter.visitorId - The [visitor ID](https://dev.fingerprint.com/docs/js-agent#visitorid) for which you want to find the other visitor IDs that originated from the same mobile device.
   *
   * @example
   * ```javascript
   * client
   *   .getRelatedVisitors({ visitor_id: '<visitorId>' })
   *   .then((relatedVisits) => {
   *     console.log(relatedVisits)
   *   })
   *  .catch((error) => {
   *    if (error instanceof RequestError) {
   *       console.log(error.statusCode, error.message)
   *       // Access raw response in error
   *       console.log(error.response)
   *
   *       if(error instanceof TooManyRequestsError) {
   *          retryLater(error.retryAfter) // Needs to be implemented on your side
   *       }
   *     }
   *   })
   * ```
   */
  async getRelatedVisitors(filter: RelatedVisitorsFilter): Promise<RelatedVisitorsResponse> {
    const url = getRequestPath({
      path: '/related-visitors',
      region: this.region,
      apiKey: this.getQueryApiKey(),
      method: 'get',
      queryParams: filter,
    })
    const headers = this.getHeaders()
 
    const response = await this.fetch(url, {
      method: 'GET',
      headers,
    })
 
    const jsonResponse = await copyResponseJson(response)
 
    if (response.status === 200) {
      return jsonResponse as RelatedVisitorsResponse
    }
 
    handleErrorResponse(jsonResponse, response)
  }
 
  private getHeaders() {
    return this.authenticationMode === AuthenticationMode.AuthHeader ? { 'Auth-API-Key': this.apiKey } : undefined
  }
 
  private getQueryApiKey() {
    return this.authenticationMode === AuthenticationMode.QueryParameter ? this.apiKey : undefined
  }
}