| const { generateCode } = require('./generateCode'); |
|
|
| async function createAccessTokenForPayment({ |
| connection, |
| paymentId, |
| clientId, |
| deviceId, |
| planId, |
| durationSeconds, |
| downLimit, |
| downUnit, |
| upLimit, |
| upUnit, |
| }) { |
| if (!connection) { |
| throw new Error('Database connection is required'); |
| } |
|
|
| let lastError = null; |
|
|
| for (let attempt = 0; attempt < 5; attempt += 1) { |
| const code = generateCode(); |
|
|
| try { |
| const [insertResult] = await connection.execute( |
| `INSERT INTO access_tokens |
| (client_id, device_id, plan_id, payment_id, code, duration_seconds, |
| down_limit, down_unit, up_limit, up_unit, status) |
| VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'unused')`, |
| [ |
| clientId, |
| deviceId, |
| planId, |
| paymentId, |
| code, |
| durationSeconds, |
| downLimit, |
| downUnit, |
| upLimit, |
| upUnit, |
| ] |
| ); |
|
|
| await connection.execute( |
| `UPDATE payments SET access_token_code = ? WHERE id = ?`, |
| [code, paymentId] |
| ); |
|
|
| return { |
| tokenId: insertResult.insertId, |
| code, |
| }; |
| } catch (err) { |
| lastError = err; |
| if (err.code !== 'ER_DUP_ENTRY') throw err; |
| } |
| } |
|
|
| throw lastError || new Error('Failed to generate a unique token code'); |
| } |
|
|
| module.exports = { createAccessTokenForPayment }; |
|
|