@@ -2,6 +2,9 @@ import { RouterContext } from 'fivem-router';
2
2
import z from 'zod' ;
3
3
import { DeviceWithSimCard } from '../../shared/Types' ;
4
4
import DeviceRepository from '../repositories/DeviceRepository' ;
5
+ import PlayerService from '../services/PlayerService' ;
6
+ import { handleError } from '../utils/errors' ;
7
+ import { DeviceNotFoundError } from '../../shared/Errors' ;
5
8
6
9
declare module 'fivem-router' {
7
10
interface RouterContext {
@@ -48,41 +51,29 @@ try {
48
51
}
49
52
50
53
export const deviceMiddleware = async ( ctx : RouterContext , next : ( ) => Promise < void > ) => {
51
- const { data : headerDeviceId } = z . coerce
52
- . number ( )
53
- . safeParse ( ctx . request ?. headers ?. [ 'x-device-id' ] ) ;
54
-
55
- let deviceIdentifier = ! headerDeviceId ? getDeviceIdentifierBySource ( ctx . source ) : '' ;
56
-
57
- if ( ! deviceIdentifier && ! headerDeviceId ) {
58
- ctx . throw ( 401 , 'Device ID not found. Are you calling this from the server?' ) ;
59
- return next ( ) ;
60
- }
54
+ const deviceIdentifier = PlayerService . getDevice ( ctx . source ) ;
61
55
62
56
try {
63
- let device ;
64
-
65
- if ( headerDeviceId ) {
66
- device = await DeviceRepository . getDeviceById ( headerDeviceId ) ;
67
- } else {
68
- device = await DeviceRepository . getDeviceByIdentifier ( deviceIdentifier ) ;
57
+ if ( ! deviceIdentifier ) {
58
+ throw new DeviceNotFoundError ( 'CALLER' ) ;
69
59
}
70
60
61
+ const device = await DeviceRepository . getDeviceByIdentifier ( deviceIdentifier ) ;
62
+
71
63
if ( ! device && ctx . url === '/devices/register' ) {
72
64
console . log ( 'Device not found, registering new device' ) ;
73
65
await next ( ) ;
74
66
return ;
75
67
}
76
68
77
69
if ( ! device ) {
78
- ctx . throw ( 401 , 'Device not found' ) ;
79
- return next ( ) ;
70
+ throw new DeviceNotFoundError ( 'CALLER' ) ;
80
71
}
81
72
82
73
ctx . device = device ;
74
+
75
+ await next ( ) ;
83
76
} catch ( error ) {
84
- ctx . throw ( 401 , 'Device not found' ) ;
77
+ handleError ( error , ctx ) ;
85
78
}
86
-
87
- await next ( ) ;
88
79
} ;
0 commit comments