-
Notifications
You must be signed in to change notification settings - Fork 20
/
objection.spec.ts
80 lines (65 loc) · 2.21 KB
/
objection.spec.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import { FieldCondition } from '@ucast/core'
import { Model, QueryBuilder } from 'objection'
import Knex from 'knex'
import { interpret } from '../src/lib/objection'
import { expect, linearize } from './specHelper'
describe('Condition interpreter for Objection', () => {
const { User } = configureORM()
it('returns `QueryBuilder`', () => {
const condition = new FieldCondition('eq', 'name', 'test')
const query = interpret(condition, User.query())
expect(query).to.be.instanceOf(QueryBuilder)
})
it('properly binds parameters', () => {
const condition = new FieldCondition('eq', 'name', 'test')
const query = interpret(condition, User.query())
expect(query.toKnexQuery().toString()).to.equal(`
select "users".* from "users" where "name" = 'test'
`.trim())
})
it('properly binds parameters for "IN" operator', () => {
const condition = new FieldCondition('in', 'age', [1, 2, 3])
const query = interpret(condition, User.query())
expect(query.toKnexQuery().toString()).to.equal(`
select "users".* from "users" where "age" in(1, 2, 3)
`.trim())
})
it('automatically inner joins relation when condition is set on relation field', () => {
const condition = new FieldCondition('eq', 'projects.name', 'test')
const query = interpret(condition, User.query())
expect(query.toKnexQuery().toString()).to.equal(linearize`
select "users".*
from "users"
inner join "projects" on "projects"."user_id" = "users"."id"
where "projects"."name" = 'test'
`.trim())
})
})
function configureORM() {
Model.knex(Knex({ client: 'pg' }))
class User extends Model {
static tableName = 'users'
static get relationMappings() {
return {
projects: {
relation: Model.HasManyRelation,
modelClass: Project,
join: { from: 'users.id', to: 'projects.user_id' }
}
}
}
}
class Project extends Model {
static tableName = 'projects'
static get relationMappings() {
return {
user: {
relation: Model.BelongsToOneRelation,
modelClass: User,
join: { from: 'users.id', to: 'projects.user_id' }
}
}
}
}
return { User, Project }
}