File size: 1,266 Bytes
9705b6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const jose = require('jose');
const jwt = require('jsonwebtoken');

/**
 * Signs a given payload using either the `jose` library (for Bun runtime) or `jsonwebtoken`.
 *
 * @async
 * @function
 * @param {Object} options - The options for signing the payload.
 * @param {Object} options.payload - The payload to be signed.
 * @param {string} options.secret - The secret key used for signing.
 * @param {number} options.expirationTime - The expiration time in seconds.
 * @returns {Promise<string>} Returns a promise that resolves to the signed JWT.
 * @throws {Error} Throws an error if there's an issue during signing.
 *
 * @example
 * const signedPayload = await signPayload({
 *   payload: { userId: 123 },
 *   secret: 'my-secret-key',
 *   expirationTime: 3600
 * });
 */
async function signPayload({ payload, secret, expirationTime }) {
  if (typeof Bun !== 'undefined') {
    // this code will only run when the file is run with Bun
    const encodedSecret = new TextEncoder().encode(secret);
    return await new jose.SignJWT(payload)
      .setProtectedHeader({ alg: 'HS256' })
      .setExpirationTime(expirationTime + 's')
      .sign(encodedSecret);
  }

  return jwt.sign(payload, secret, { expiresIn: expirationTime });
}

module.exports = signPayload;