mirror of https://github.com/wg-easy/wg-easy
committed by
GitHub
3 changed files with 86 additions and 30 deletions
@ -0,0 +1,30 @@ |
|||
type StatusFields = { |
|||
publicKey: string; |
|||
latestHandshakeAt: Date | null; |
|||
endpoint: string | null; |
|||
transferRx: number | null; |
|||
transferTx: number | null; |
|||
}; |
|||
|
|||
export function mergeClientStatuses<T extends StatusFields>( |
|||
clients: T[], |
|||
statuses: readonly StatusFields[] |
|||
): T[] { |
|||
const clientsByPublicKey = new Map( |
|||
clients.map((client) => [client.publicKey, client]) |
|||
); |
|||
|
|||
for (const status of statuses) { |
|||
const client = clientsByPublicKey.get(status.publicKey); |
|||
if (!client) { |
|||
continue; |
|||
} |
|||
|
|||
client.latestHandshakeAt = status.latestHandshakeAt; |
|||
client.endpoint = status.endpoint; |
|||
client.transferRx = status.transferRx; |
|||
client.transferTx = status.transferTx; |
|||
} |
|||
|
|||
return clients; |
|||
} |
|||
@ -0,0 +1,53 @@ |
|||
import { describe, expect, test } from 'vitest'; |
|||
|
|||
import { mergeClientStatuses } from '#server/utils/clientStatus'; |
|||
|
|||
describe('mergeClientStatuses', () => { |
|||
test('merges matching status records by public key', () => { |
|||
const clients = [ |
|||
{ |
|||
id: 1, |
|||
publicKey: 'first', |
|||
latestHandshakeAt: null, |
|||
endpoint: null, |
|||
transferRx: null, |
|||
transferTx: null, |
|||
}, |
|||
{ |
|||
id: 2, |
|||
publicKey: 'second', |
|||
latestHandshakeAt: null, |
|||
endpoint: null, |
|||
transferRx: null, |
|||
transferTx: null, |
|||
}, |
|||
]; |
|||
const handshake = new Date('2026-07-20T00:00:00Z'); |
|||
|
|||
const result = mergeClientStatuses(clients, [ |
|||
{ |
|||
publicKey: 'second', |
|||
latestHandshakeAt: handshake, |
|||
endpoint: '192.0.2.1:51820', |
|||
transferRx: 100, |
|||
transferTx: 200, |
|||
}, |
|||
{ |
|||
publicKey: 'unknown', |
|||
latestHandshakeAt: null, |
|||
endpoint: null, |
|||
transferRx: 0, |
|||
transferTx: 0, |
|||
}, |
|||
]); |
|||
|
|||
expect(result).toBe(clients); |
|||
expect(result[0]?.endpoint).toBeNull(); |
|||
expect(result[1]).toMatchObject({ |
|||
latestHandshakeAt: handshake, |
|||
endpoint: '192.0.2.1:51820', |
|||
transferRx: 100, |
|||
transferTx: 200, |
|||
}); |
|||
}); |
|||
}); |
|||
Loading…
Reference in new issue