Skip to content

Commit 41d4c8c

Browse files
authored
feat: add the new method to create and persist entry with default values (#57) (#68)
close #57
1 parent 998423a commit 41d4c8c

File tree

3 files changed

+58
-0
lines changed

3 files changed

+58
-0
lines changed

src/query/Query.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -379,6 +379,17 @@ export class Query<M extends Model = Model> {
379379
return this.model.$getRelation(name)
380380
}
381381

382+
/**
383+
* Create and persist model with default values.
384+
*/
385+
async new(): Promise<M> {
386+
const model = this.model.$newInstance(undefined, { relations: false })
387+
388+
this.connection.insert(this.compile(model))
389+
390+
return model
391+
}
392+
382393
/**
383394
* Insert the given record to the store.
384395
*/

src/repository/Repository.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,13 @@ export class Repository<M extends Model = Model> {
174174
})
175175
}
176176

177+
/**
178+
* Create and persist model with default values.
179+
*/
180+
new(): Promise<M> {
181+
return this.query().new()
182+
}
183+
177184
/**
178185
* Insert the given records to the store.
179186
*/
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import { createStore, assertState, mockUid } from 'test/Helpers'
2+
import { Model, Str, Num, Bool, Uid, Attr } from '@/index'
3+
4+
describe('feature/repository/inserts_new', () => {
5+
it('inserts with a models default values', async () => {
6+
class User extends Model {
7+
static entity = 'users'
8+
9+
@Uid() id!: string
10+
@Str('John Doe') name!: string
11+
@Num(21) age!: number
12+
@Bool(true) active!: boolean
13+
}
14+
15+
mockUid(['uid1'])
16+
17+
const store = createStore()
18+
19+
await store.$repo(User).new()
20+
21+
assertState(store, {
22+
users: {
23+
uid1: { id: 'uid1', name: 'John Doe', age: 21, active: true }
24+
}
25+
})
26+
})
27+
28+
it('throws if a primary key is not capable of being generated', async () => {
29+
class User extends Model {
30+
static entity = 'users'
31+
32+
@Attr() id!: any
33+
@Str('John Doe') name!: string
34+
}
35+
36+
const store = createStore()
37+
38+
await expect(() => store.$repo(User).new()).rejects.toThrow()
39+
})
40+
})

0 commit comments

Comments
 (0)