-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathobjectql-adapter.test.ts
More file actions
325 lines (291 loc) · 12.1 KB
/
Copy pathobjectql-adapter.test.ts
File metadata and controls
325 lines (291 loc) · 12.1 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import { describe, it, expect, vi, beforeEach } from 'vitest';
import {
createObjectQLAdapter,
createObjectQLAdapterFactory,
AUTH_MODEL_TO_PROTOCOL,
resolveProtocolName,
} from './objectql-adapter';
import {
AUTH_USER_CONFIG,
AUTH_SESSION_CONFIG,
AUTH_ACCOUNT_CONFIG,
AUTH_VERIFICATION_CONFIG,
AUTH_ORGANIZATION_SCHEMA,
AUTH_MEMBER_SCHEMA,
AUTH_INVITATION_SCHEMA,
AUTH_TEAM_SCHEMA,
AUTH_TEAM_MEMBER_SCHEMA,
AUTH_TWO_FACTOR_SCHEMA,
AUTH_ORG_SESSION_FIELDS,
buildOrganizationPluginSchema,
buildTwoFactorPluginSchema,
} from './auth-schema-config';
import { SystemObjectName } from '@objectstack/spec/system';
import type { IDataEngine } from '@objectstack/core';
import { sso } from '@better-auth/sso';
describe('AUTH_MODEL_TO_PROTOCOL mapping', () => {
it('should map all four core better-auth models to sys_ protocol names', () => {
expect(AUTH_MODEL_TO_PROTOCOL.user).toBe('sys_user');
expect(AUTH_MODEL_TO_PROTOCOL.session).toBe('sys_session');
expect(AUTH_MODEL_TO_PROTOCOL.account).toBe('sys_account');
expect(AUTH_MODEL_TO_PROTOCOL.verification).toBe('sys_verification');
});
it('should align with SystemObjectName constants', () => {
expect(AUTH_MODEL_TO_PROTOCOL.user).toBe(SystemObjectName.USER);
expect(AUTH_MODEL_TO_PROTOCOL.session).toBe(SystemObjectName.SESSION);
expect(AUTH_MODEL_TO_PROTOCOL.account).toBe(SystemObjectName.ACCOUNT);
expect(AUTH_MODEL_TO_PROTOCOL.verification).toBe(SystemObjectName.VERIFICATION);
});
});
describe('resolveProtocolName', () => {
it('should resolve core models to sys_ prefixed names', () => {
expect(resolveProtocolName('user')).toBe('sys_user');
expect(resolveProtocolName('session')).toBe('sys_session');
expect(resolveProtocolName('account')).toBe('sys_account');
expect(resolveProtocolName('verification')).toBe('sys_verification');
});
it('should fall back to original name for unknown models', () => {
expect(resolveProtocolName('organization')).toBe('organization');
expect(resolveProtocolName('custom_model')).toBe('custom_model');
});
});
describe('AUTH_*_CONFIG schema mappings', () => {
it('should define correct modelName for all core models', () => {
expect(AUTH_USER_CONFIG.modelName).toBe('sys_user');
expect(AUTH_SESSION_CONFIG.modelName).toBe('sys_session');
expect(AUTH_ACCOUNT_CONFIG.modelName).toBe('sys_account');
expect(AUTH_VERIFICATION_CONFIG.modelName).toBe('sys_verification');
});
it('should map user camelCase fields to snake_case', () => {
expect(AUTH_USER_CONFIG.fields).toEqual({
emailVerified: 'email_verified',
createdAt: 'created_at',
updatedAt: 'updated_at',
});
});
it('should map session camelCase fields to snake_case', () => {
expect(AUTH_SESSION_CONFIG.fields).toEqual({
userId: 'user_id',
expiresAt: 'expires_at',
createdAt: 'created_at',
updatedAt: 'updated_at',
ipAddress: 'ip_address',
userAgent: 'user_agent',
});
});
it('should map account camelCase fields to snake_case', () => {
expect(AUTH_ACCOUNT_CONFIG.fields).toEqual({
userId: 'user_id',
providerId: 'provider_id',
accountId: 'account_id',
accessToken: 'access_token',
refreshToken: 'refresh_token',
idToken: 'id_token',
accessTokenExpiresAt: 'access_token_expires_at',
refreshTokenExpiresAt: 'refresh_token_expires_at',
createdAt: 'created_at',
updatedAt: 'updated_at',
});
});
it('should map verification camelCase fields to snake_case', () => {
expect(AUTH_VERIFICATION_CONFIG.fields).toEqual({
expiresAt: 'expires_at',
createdAt: 'created_at',
updatedAt: 'updated_at',
});
});
});
describe('AUTH_*_SCHEMA plugin table mappings', () => {
it('should define organization model mapping', () => {
expect(AUTH_ORGANIZATION_SCHEMA.modelName).toBe('sys_organization');
expect(AUTH_ORGANIZATION_SCHEMA.fields).toEqual({
createdAt: 'created_at',
updatedAt: 'updated_at',
});
});
it('should define member model mapping', () => {
expect(AUTH_MEMBER_SCHEMA.modelName).toBe('sys_member');
expect(AUTH_MEMBER_SCHEMA.fields).toEqual({
organizationId: 'organization_id',
userId: 'user_id',
createdAt: 'created_at',
});
});
it('should define invitation model mapping', () => {
expect(AUTH_INVITATION_SCHEMA.modelName).toBe('sys_invitation');
expect(AUTH_INVITATION_SCHEMA.fields).toEqual({
organizationId: 'organization_id',
inviterId: 'inviter_id',
expiresAt: 'expires_at',
createdAt: 'created_at',
teamId: 'team_id',
});
});
it('should define team model mapping', () => {
expect(AUTH_TEAM_SCHEMA.modelName).toBe('sys_team');
expect(AUTH_TEAM_SCHEMA.fields).toEqual({
organizationId: 'organization_id',
createdAt: 'created_at',
updatedAt: 'updated_at',
});
});
it('should define team member model mapping', () => {
expect(AUTH_TEAM_MEMBER_SCHEMA.modelName).toBe('sys_team_member');
expect(AUTH_TEAM_MEMBER_SCHEMA.fields).toEqual({
teamId: 'team_id',
userId: 'user_id',
createdAt: 'created_at',
});
});
it('should define two-factor model mapping', () => {
expect(AUTH_TWO_FACTOR_SCHEMA.modelName).toBe('sys_two_factor');
expect(AUTH_TWO_FACTOR_SCHEMA.fields).toEqual({
backupCodes: 'backup_codes',
userId: 'user_id',
});
});
it('should define org session additional fields', () => {
expect(AUTH_ORG_SESSION_FIELDS).toEqual({
activeOrganizationId: 'active_organization_id',
activeTeamId: 'active_team_id',
});
});
});
describe('buildOrganizationPluginSchema', () => {
it('should compose all org plugin table schemas', () => {
const schema = buildOrganizationPluginSchema();
expect(schema.organization).toBe(AUTH_ORGANIZATION_SCHEMA);
expect(schema.member).toBe(AUTH_MEMBER_SCHEMA);
expect(schema.invitation).toBe(AUTH_INVITATION_SCHEMA);
expect(schema.team).toBe(AUTH_TEAM_SCHEMA);
expect(schema.teamMember).toBe(AUTH_TEAM_MEMBER_SCHEMA);
expect(schema.session.fields).toBe(AUTH_ORG_SESSION_FIELDS);
});
});
describe('buildTwoFactorPluginSchema', () => {
it('should compose two-factor model + user field schema', () => {
const schema = buildTwoFactorPluginSchema();
expect(schema.twoFactor).toBe(AUTH_TWO_FACTOR_SCHEMA);
expect(schema.user.fields).toEqual({
twoFactorEnabled: 'two_factor_enabled',
});
});
});
describe('createObjectQLAdapterFactory', () => {
it('should return a function (adapter factory)', () => {
const mockEngine = {
insert: vi.fn(),
findOne: vi.fn(),
find: vi.fn(),
count: vi.fn(),
update: vi.fn(),
delete: vi.fn(),
} as unknown as IDataEngine;
const factory = createObjectQLAdapterFactory(mockEngine);
expect(typeof factory).toBe('function');
});
});
describe('createObjectQLAdapter – legacy model name mapping', () => {
let mockEngine: IDataEngine;
beforeEach(() => {
mockEngine = {
insert: vi.fn().mockResolvedValue({ id: '1' }),
findOne: vi.fn().mockResolvedValue({ id: '1' }),
find: vi.fn().mockResolvedValue([]),
count: vi.fn().mockResolvedValue(0),
update: vi.fn().mockResolvedValue({ id: '1' }),
delete: vi.fn().mockResolvedValue(undefined),
} as unknown as IDataEngine;
});
it('create: should call dataEngine.insert with sys_ protocol name', async () => {
const adapter = createObjectQLAdapter(mockEngine);
await adapter.create({ model: 'user', data: { email: 'a@b.com' } });
expect(mockEngine.insert).toHaveBeenCalledWith('sys_user', { email: 'a@b.com' });
});
it('findOne: should call dataEngine.findOne with sys_ protocol name', async () => {
const adapter = createObjectQLAdapter(mockEngine);
await adapter.findOne({
model: 'session',
where: [{ field: 'token', value: 'abc', operator: 'eq', connector: 'AND' }],
});
expect(mockEngine.findOne).toHaveBeenCalledWith('sys_session', expect.objectContaining({
where: { token: 'abc' },
}));
});
it('findMany: should call dataEngine.find with sys_ protocol name', async () => {
const adapter = createObjectQLAdapter(mockEngine);
await adapter.findMany({ model: 'account', limit: 10 });
expect(mockEngine.find).toHaveBeenCalledWith('sys_account', expect.objectContaining({
limit: 10,
}));
});
it('count: should call dataEngine.count with sys_ protocol name', async () => {
const adapter = createObjectQLAdapter(mockEngine);
await adapter.count({ model: 'verification' });
expect(mockEngine.count).toHaveBeenCalledWith('sys_verification', expect.anything());
});
it('update: should call dataEngine with sys_ protocol name', async () => {
const adapter = createObjectQLAdapter(mockEngine);
await adapter.update({
model: 'user',
where: [{ field: 'id', value: '1', operator: 'eq', connector: 'AND' }],
update: { name: 'New' },
});
expect(mockEngine.findOne).toHaveBeenCalledWith('sys_user', expect.anything());
expect(mockEngine.update).toHaveBeenCalledWith('sys_user', expect.objectContaining({ name: 'New', id: '1' }));
});
it('delete: should call dataEngine with sys_ protocol name', async () => {
const adapter = createObjectQLAdapter(mockEngine);
await adapter.delete({
model: 'session',
where: [{ field: 'id', value: '1', operator: 'eq', connector: 'AND' }],
});
expect(mockEngine.findOne).toHaveBeenCalledWith('sys_session', expect.anything());
expect(mockEngine.delete).toHaveBeenCalledWith('sys_session', expect.anything());
});
it('should pass through unknown model names unchanged', async () => {
const adapter = createObjectQLAdapter(mockEngine);
await adapter.create({ model: 'organization', data: { name: 'Acme' } });
expect(mockEngine.insert).toHaveBeenCalledWith('organization', { name: 'Acme' });
});
});
describe('createObjectQLAdapterFactory – schema-less plugin bridging (@better-auth/sso)', () => {
// The sso plugin exposes no `schema` option, so its `ssoProvider` table +
// camelCase fields are bridged at the adapter layer. Pass the plugin so
// better-auth's wrapper recognises the model (it validates against the
// merged schema before delegating to our adapter methods).
const makeAdapter = (findOneRow: any = { id: '1', provider_id: 'okta', oidc_config: '{"clientId":"x"}', domain: 'acme.com' }) => {
const engine = {
insert: vi.fn().mockImplementation((_m: string, d: any) => Promise.resolve({ id: '1', ...d })),
findOne: vi.fn().mockResolvedValue(findOneRow),
find: vi.fn().mockResolvedValue([]),
count: vi.fn().mockResolvedValue(0),
update: vi.fn().mockResolvedValue({ id: '1' }),
delete: vi.fn().mockResolvedValue(undefined),
} as unknown as IDataEngine;
const adapter: any = (createObjectQLAdapterFactory(engine) as any)({ plugins: [sso()] } as any);
return { engine, adapter };
};
it('resolveProtocolName bridges ssoProvider -> sys_sso_provider', () => {
expect(resolveProtocolName('ssoProvider')).toBe('sys_sso_provider');
expect(AUTH_MODEL_TO_PROTOCOL.ssoProvider).toBe('sys_sso_provider');
});
it('maps the ssoProvider model + camelCase fields to sys_sso_provider snake columns on insert', async () => {
const { engine, adapter } = makeAdapter();
await adapter.create({ model: 'ssoProvider', data: { providerId: 'okta', oidcConfig: '{"clientId":"x"}', domain: 'acme.com' } });
const [tbl, payload] = (engine.insert as any).mock.calls[0];
expect(tbl).toBe('sys_sso_provider');
expect(payload).toMatchObject({ provider_id: 'okta', oidc_config: '{"clientId":"x"}', domain: 'acme.com' });
expect(payload).not.toHaveProperty('oidcConfig');
});
it('maps snake columns back to camelCase on read', async () => {
const { adapter } = makeAdapter();
const row: any = await adapter.findOne({
model: 'ssoProvider',
where: [{ field: 'providerId', value: 'okta', operator: 'eq', connector: 'AND' }],
});
expect(row).toMatchObject({ providerId: 'okta', oidcConfig: '{"clientId":"x"}' });
expect(row).not.toHaveProperty('oidc_config');
});
});