Skip to content

Commit 538598a

Browse files
committed
feat: add make method to create a new model instance
1 parent e70e32b commit 538598a

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

src/repository/Repository.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,17 @@ export class Repository<M extends Model> {
9494
return this.query().find(ids)
9595
}
9696

97+
/**
98+
* Create a new model instance. This method will not save the model to the
99+
* store. It's pretty much the alternative to `new Model()`, but it injects
100+
* the store instance to support model instance methods in SSR environment.
101+
*/
102+
make(attributes?: Element): M {
103+
return this.model.$newInstance(attributes, {
104+
relations: false
105+
})
106+
}
107+
97108
/**
98109
* Insert the given record to the store.
99110
*/
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import { createStore, assertModel } from 'test/Helpers'
2+
import { Model, Attr, Str } from '@/index'
3+
4+
describe('unit/repository/Repository', () => {
5+
class User extends Model {
6+
static entity = 'users'
7+
8+
@Attr() id!: any
9+
@Str('John Doe') name!: string
10+
}
11+
12+
it('creates a new model instance', () => {
13+
const store = createStore([User])
14+
15+
const user = store.$repo(User).make()
16+
17+
expect(user).toBeInstanceOf(User)
18+
expect(user.$store).toBe(store)
19+
assertModel(user, { id: null, name: 'John Doe' })
20+
})
21+
22+
it('creates a new model instance with default values', () => {
23+
const store = createStore([User])
24+
25+
const user = store.$repo(User).make({
26+
id: 1,
27+
name: 'Jane Doe'
28+
})
29+
30+
expect(user).toBeInstanceOf(User)
31+
expect(user.$store).toBe(store)
32+
assertModel(user, { id: 1, name: 'Jane Doe' })
33+
})
34+
})

0 commit comments

Comments
 (0)