|
| 1 | +import { createRequire } from 'node:module'; |
| 2 | +import path from 'node:path'; |
| 3 | +import { fileURLToPath, pathToFileURL } from 'node:url'; |
| 4 | + |
| 5 | +const currentDir = path.dirname(fileURLToPath(import.meta.url)); |
| 6 | +const applicationDir = path.resolve(currentDir, '../application'); |
| 7 | + |
| 8 | +// resolves to the BUILT package (adminforth/dist) the test application runs on; |
| 9 | +// rebuild it (`npx tsc` in adminforth/) after editing configValidator or the assertions below test stale code |
| 10 | +const require = createRequire(import.meta.url); |
| 11 | +const adminforthEntry = require.resolve('adminforth', { paths: [applicationDir] }); |
| 12 | +const { default: AdminForth } = await import(pathToFileURL(adminforthEntry).href); |
| 13 | + |
| 14 | +function appWithPkColumn(pkColumn: Record<string, unknown>) { |
| 15 | + // AdminForth allows one instance per process; each test needs a fresh one |
| 16 | + delete (globalThis as any).adminforth; |
| 17 | + return new AdminForth({ |
| 18 | + baseUrl: '', |
| 19 | + auth: { |
| 20 | + usersResourceId: 'adminuser', |
| 21 | + usernameField: 'email', |
| 22 | + passwordHashField: 'password_hash', |
| 23 | + }, |
| 24 | + dataSources: [{ id: 'sqlite', url: `sqlite://${path.join(applicationDir, '.db.sqlite')}` }], |
| 25 | + resources: [{ |
| 26 | + resourceId: 'adminuser', |
| 27 | + table: 'adminuser', |
| 28 | + dataSource: 'sqlite', |
| 29 | + columns: [ |
| 30 | + { name: 'id', primaryKey: true, ...pkColumn }, |
| 31 | + { name: 'email', required: true }, |
| 32 | + { name: 'password_hash', backendOnly: true }, |
| 33 | + ], |
| 34 | + }], |
| 35 | + menu: [{ label: 'Users', resourceId: 'adminuser' }], |
| 36 | + }); |
| 37 | +} |
| 38 | + |
| 39 | +const pkBackendOnlyError = /column "id" is a primary key and cannot be backendOnly/; |
| 40 | + |
| 41 | +describe('primary key column cannot be backendOnly', () => { |
| 42 | + it('rejects backendOnly: true on the primary key', () => { |
| 43 | + expect(() => appWithPkColumn({ backendOnly: true })).toThrow(pkBackendOnlyError); |
| 44 | + }); |
| 45 | + |
| 46 | + it('rejects backendOnly function on the primary key', () => { |
| 47 | + expect(() => appWithPkColumn({ backendOnly: () => false })).toThrow(pkBackendOnlyError); |
| 48 | + }); |
| 49 | + |
| 50 | + it('accepts backendOnly: false on the primary key and backendOnly on other columns', () => { |
| 51 | + expect(() => appWithPkColumn({ backendOnly: false })).not.toThrow(); |
| 52 | + expect(() => appWithPkColumn({})).not.toThrow(); |
| 53 | + }); |
| 54 | +}); |
0 commit comments