Skip to content

Commit 07f7652

Browse files
committed
msw/session: Implement apiToken model
1 parent 235c5c3 commit 07f7652

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import { nullable, oneOf, primaryKey } from '@mswjs/data';
2+
3+
import { applyDefault } from './-utils.js';
4+
5+
export const apiToken = {
6+
id: primaryKey(Number),
7+
8+
crateScopes: nullable(Array),
9+
createdAt: '2017-11-19T17:59:22',
10+
endpointScopes: nullable(Array),
11+
expiredAt: nullable(String),
12+
lastUsedAt: nullable(String),
13+
name: i => `API Token ${i + 1}`,
14+
token: String,
15+
16+
user: oneOf('user'),
17+
18+
preCreate(attrs, counter) {
19+
applyDefault(attrs, 'id', () => counter);
20+
applyDefault(attrs, 'crateScopes', () => null);
21+
applyDefault(attrs, 'endpointScopes', () => null);
22+
applyDefault(attrs, 'expiredAt', () => null);
23+
applyDefault(attrs, 'lastUsedAt', () => null);
24+
applyDefault(attrs, 'name', attrs => `API Token ${attrs.id}`);
25+
applyDefault(attrs, 'token', () => generateToken());
26+
27+
if (!attrs.user) {
28+
throw new Error('Missing `user` relationship on `api-token`');
29+
}
30+
},
31+
};
32+
33+
function generateToken() {
34+
return Math.random().toString().slice(2);
35+
}
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
1+
import { apiToken } from './api-token.js';
12
import { mswSession } from './msw-session.js';
23
import { user } from './user.js';
34

45
export const models = {
6+
apiToken,
57
mswSession,
68
user,
79
};

0 commit comments

Comments
 (0)