-
Notifications
You must be signed in to change notification settings - Fork 21
/
use-request.js
49 lines (40 loc) · 1.38 KB
/
use-request.js
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
const { AsyncLocalStorage } = require('node:async_hooks');
const { invariant } = require('ts-invariant');
const requestStorage = new AsyncLocalStorage();
/**
* An express middleware. Captures the request in AsyncLocalStorage for later
* retrieval.
*/
function requestProviderMiddleware(req, res, next) {
requestStorage.run(req, next);
}
/**
* Get the request object currently being handled by express.
* @returns {Request}
*/
function useRequest() {
return requestStorage.getStore();
}
function useSession() {
const { session } = useRequest();
invariant(session != null, 'You called useSession, but a session was not available. Consider specifying requireUser on the affected route.');
return session;
}
function useUser() {
const { user } = useSession();
invariant(user != null, 'You called useUser, but a user was not found. Consider specifying requireUser on the affected route.');
return user;
}
/** A shortcut helper to get at tenant_id directly */
function useTenantId() {
const tenantId = useUser().tenant_id;
invariant(tenantId != null, 'You called useTenantId, but a tenantId was not found.');
return tenantId;
}
module.exports = {
requestProviderMiddleware,
useRequest,
useUser,
useTenantId,
};
// NOTE: This file was copied from src/server/use-request.js (git @ ada8bfdc98) in the arpa-reporter repo on 2022-09-23T20:05:47.735Z