Skip to content

Commit 2e0f341

Browse files
authored
feat: throw error when accessing model.$store without store being injected (#2)
1 parent 1e9dcff commit 2e0f341

File tree

3 files changed

+28
-1
lines changed

3 files changed

+28
-1
lines changed

src/model/Model.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { Store } from 'vuex'
2-
import { isArray } from '../support/Utils'
2+
import { isArray, assert } from '../support/Utils'
33
import { Element, Item, Collection } from '../data/Data'
44
import { Attribute } from './attributes/Attribute'
55
import { Attr } from './attributes/types/Attr'
@@ -194,6 +194,12 @@ export class Model {
194194
* Get the store instance.
195195
*/
196196
get $store(): Store<any> {
197+
assert(this._store !== undefined, [
198+
'A Vuex Store instance is not injected into the model instance.',
199+
'You might be trying to instantiate the model directly. Please use',
200+
'`repository.make` method to create a new model instance.'
201+
])
202+
197203
return this._store
198204
}
199205

src/support/Utils.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -198,3 +198,13 @@ export function cloneDeep<T extends object>(target: T): T {
198198

199199
return target
200200
}
201+
202+
/**
203+
* Check for the given condition, and if it's `false`, it will throw a new
204+
* error with the given message.
205+
*/
206+
export function assert(condition: boolean, message: string[]): void {
207+
if (!condition) {
208+
throw new Error(['[Vuex ORM]'].concat(message).join(' '))
209+
}
210+
}

test/unit/model/Model.spec.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import { Model } from '@/model/Model'
2+
3+
describe('unit/model/Model', () => {
4+
class User extends Model {
5+
static entity = 'users'
6+
}
7+
8+
it('throws when accessing the store but it is not injected', () => {
9+
expect(() => new User().$store).toThrow()
10+
})
11+
})

0 commit comments

Comments
 (0)