aboutsummaryrefslogtreecommitdiff
path: root/packages/taler-util/src/http-client/utils.ts
blob: 4588f945c86b615f5447071e6bbf8c2595bbd0de (plain)
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
import { base64FromArrayBuffer } from "../base64.js";
import { stringToBytes } from "../taler-crypto.js";
import { AccessToken, TalerAuthentication } from "./types.js";

/**
 * Helper function to generate the "Authorization" HTTP header.
 */
export function makeBasicAuthHeader(username: string, password: string): string {
  const auth = `${username}:${password}`;
  const authEncoded: string = base64FromArrayBuffer(stringToBytes(auth));
  return `Basic ${authEncoded}`;
}

/**
 * rfc8959
 * @param token 
 * @returns 
 */
export function makeBearerTokenAuthHeader(token: AccessToken): string {
  return `Bearer secret-token:${token}`;
}

/**
 * https://bugs.gnunet.org/view.php?id=7949
 */
export function addPaginationParams(url: URL, pagination?: PaginationParams) {
  if (!pagination) return;
  if (pagination.timoutMs) {
    url.searchParams.set("long_poll_ms", String(pagination.timoutMs))
  }
  if (pagination.offset) {
    url.searchParams.set("start", pagination.offset)
  }
  const order = !pagination || pagination.order === "asc" ? 1 : -1
  const limit = !pagination || !pagination.limit || pagination.limit === 0 ? 5 : Math.abs(pagination.limit)
  //always send delta
  url.searchParams.set("delta", String(order * limit))
}

export type UserAndPassword = {
  username: string,
  password: string,
}

export type UserAndToken = {
  username: string,
  token: AccessToken,
}

export type PaginationParams = {
  /**
   * row identifier as the starting point of the query
   */
  offset?: string,
  /**
   * max number of element in the result response
   * always greater than 0
   */
  limit?: number,
  /**
   * milliseconds the server should wait for at least one result to be shown
   */
  timoutMs?: number,
  /**
   * order
   */
  order: "asc" | "dec"
}