Skip to content

Commit 5c40abd

Browse files
authored
feat: add assign id function (#10)
1 parent a2dade9 commit 5c40abd

File tree

3 files changed

+48
-1
lines changed

3 files changed

+48
-1
lines changed

README.md

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,17 @@ Typically, the backend creates new `id` for each `POST /resource` call that does
9191
{ rest: { assignId: true, todos: 'todos.json' } }
9292
```
9393
94+
You can also pass your own synchronous function to return an id
95+
96+
```js
97+
{
98+
rest: {
99+
assignId: () => '123-abc',
100+
todos: 'todos.json',
101+
},
102+
}
103+
```
104+
94105
## Small print
95106
96107
Author: Gleb Bahmutov <gleb.bahmutov@gmail.com> © 2025
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/// <reference types="cypress" />
2+
3+
chai.config.truncateThreshold = 0
4+
5+
describe(
6+
'Todos with server-side ID',
7+
{
8+
rest: {
9+
assignId: () => '123-abc',
10+
todos: 'todos.json',
11+
},
12+
},
13+
() => {
14+
beforeEach(() => {
15+
cy.visit('app-server-id/index.html')
16+
cy.contains('h1', 'Server ID')
17+
})
18+
19+
it('uses custom stub to create server id', () => {
20+
cy.get('input.new-todo').type('Buy milk{enter}')
21+
22+
cy.step('Check the created UUID')
23+
cy.contains('li.todo', 'Buy milk').should(
24+
'have.attr',
25+
'data-todo-id',
26+
'123-abc',
27+
)
28+
})
29+
},
30+
)

src/index.js

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,13 @@ beforeEach(function prepareRestApi() {
4747
const item = structuredClone(req.body)
4848
// modify the id?
4949
if (assignId && !('id' in item)) {
50-
item.id = crypto.randomUUID()
50+
if (assignId === true) {
51+
item.id = crypto.randomUUID()
52+
} else if (typeof assignId === 'function') {
53+
item.id = assignId()
54+
} else {
55+
throw new Error('assignId has invalid value')
56+
}
5157
}
5258
data.push(item)
5359
req.reply(201, item)

0 commit comments

Comments
 (0)