Skip to content

Commit f8e152c

Browse files
committed
add tests for 'externalIdMapping'
1 parent 384bcf9 commit f8e152c

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed

packages/server/tests/api/rest.test.ts

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3111,4 +3111,87 @@ describe('REST server tests', () => {
31113111
});
31123112
});
31133113
});
3114+
3115+
describe('REST server tests - external id mapping', () => {
3116+
const schema = `
3117+
model User {
3118+
id Int @id @default(autoincrement())
3119+
name String
3120+
source String
3121+
posts Post[]
3122+
3123+
@@unique([name, source])
3124+
}
3125+
3126+
model Post {
3127+
id Int @id @default(autoincrement())
3128+
title String
3129+
author User? @relation(fields: [authorId], references: [id])
3130+
authorId Int?
3131+
}
3132+
`;
3133+
beforeAll(async () => {
3134+
const params = await loadSchema(schema);
3135+
prisma = params.prisma;
3136+
zodSchemas = params.zodSchemas;
3137+
modelMeta = params.modelMeta;
3138+
3139+
const _handler = makeHandler({
3140+
endpoint: 'http://localhost/api',
3141+
externalIdMapping: {
3142+
User: 'name_source',
3143+
},
3144+
});
3145+
handler = (args) =>
3146+
_handler({ ...args, zodSchemas, modelMeta, url: new URL(`http://localhost/${args.path}`) });
3147+
});
3148+
3149+
it('works with id mapping', async () => {
3150+
await prisma.user.create({
3151+
data: { id: 1, name: 'User1', source: 'a' },
3152+
});
3153+
3154+
// user is no longer exposed using the `id` field
3155+
let r = await handler({
3156+
method: 'get',
3157+
path: '/user/1',
3158+
query: {},
3159+
prisma,
3160+
});
3161+
3162+
expect(r.status).toBe(400);
3163+
3164+
// user is exposed using the fields from the `name__source` multi-column unique index
3165+
r = await handler({
3166+
method: 'get',
3167+
path: '/user/User1_a',
3168+
query: {},
3169+
prisma,
3170+
});
3171+
3172+
expect(r.status).toBe(200);
3173+
expect(r.body.data.attributes.source).toBe('a');
3174+
expect(r.body.data.attributes.name).toBe('User1');
3175+
3176+
await prisma.post.create({
3177+
data: { id: 1, title: 'Title1', authorId: 1 },
3178+
});
3179+
3180+
// post is exposed using the `id` field
3181+
r = await handler({
3182+
method: 'get',
3183+
path: '/post/1',
3184+
query: { include: 'author' },
3185+
prisma,
3186+
});
3187+
3188+
expect(r.status).toBe(200);
3189+
expect(r.body.data.attributes.title).toBe('Title1');
3190+
// Verify author relationship contains the external ID
3191+
expect(r.body.data.relationships.author.data).toMatchObject({
3192+
type: 'user',
3193+
id: 'User1_a',
3194+
});
3195+
});
3196+
});
31143197
});

0 commit comments

Comments
 (0)