Skip to content

Commit

Permalink
fix: create nested data with composite key
Browse files Browse the repository at this point in the history
  • Loading branch information
kkyouhei committed Apr 20, 2019
1 parent 37dc718 commit ec02683
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/model/Model.ts
Expand Up @@ -15,6 +15,7 @@ import * as Payloads from '../modules/payloads/Actions'
import Fields from './contracts/Fields'
import ModelState from './contracts/State'
import Serializer from './Serializer'
import NoKey from '../schema/NoKey'

type InstanceOf<T> = T extends new (...args: any[]) => infer R ? R : any

Expand Down Expand Up @@ -391,7 +392,7 @@ export default class Model {
return record[key]
}

return key.map(k => record[k]).join('_')
return key.map(k => (record[k] || NoKey.increment())).join('_')
}

/**
Expand Down
43 changes: 43 additions & 0 deletions test/feature/relations/BelongsTo.spec.js
Expand Up @@ -90,6 +90,49 @@ describe('Features – Relations – Belongs To', () => {
expect(store.state.entities).toEqual(expected)
})

it('can generate relation field with composite key', () => {
class User extends Model {
static entity = 'users'

static fields() {
return {
id: this.attr(null)
}
}
}

class Post extends Model {
static entity = 'posts'
static primaryKey = ['id', 'user_id']

static fields() {
return {
id: this.attr(null),
user_id: this.attr(null),
user: this.belongsTo(User, 'user_id')
}
}
}

const store = createStore([{ model: User }, { model: Post }])

store.dispatch('entities/posts/create', {
data: [
{ id: 1, user: { id: 10 } },
{ id: 1, user: { id: 20 } }
]
})

expect(store.state.entities.users.data[10].id).toBe(10)
expect(store.state.entities.users.data[20].id).toBe(20)
expect(store.state.entities.posts.data['1_10'].$id).toBe('1_10')
expect(store.state.entities.posts.data['1_10'].id).toBe(1)
expect(store.state.entities.posts.data['1_10'].user_id).toBe(10)
expect(store.state.entities.posts.data['1_20'].$id).toBe('1_20')
expect(store.state.entities.posts.data['1_20'].id).toBe(1)
expect(store.state.entities.posts.data['1_20'].user_id).toBe(20)
})

it('returns created record from `create` method', async () => {
const store = createStore([{ model: User }, { model: Post }])

Expand Down

0 comments on commit ec02683

Please sign in to comment.