query.coffee | |
|---|---|
Query for tasksRich mechanism to specify exactly which tasks you would like, using property comparisons, limits and other constraints. A A simple fetch of 10 tasks ordered by their
Where | |
| Requirements | _ = require 'underscore'
Connection = require('./connection').Connection |
| Task top level properties | top_level =
id: true
name: true
project_id: true
template_id: true
duplication: true
replication: true
created_at: true
updated_at: true
expires_at: true
responses: true
class Query extends Connection
constructor: ->
@get_path = 'tasks.json'
@constraints = []
@ordering = false
@limited = false |
| Check for equality of any property, usually in
Top level properties like | eq: (prop, value) ->
@constraints.push op: 'eq', prop: prop, value: value
this |
| Synonym for | where: Query::eq |
| Inequailty of a property in | ne: (prop, value) ->
@constraints.push op: 'ne', prop: prop, value: value
this |
| Check if the task has been answered | iscomplete: (value) ->
@constraints.push op: 'iscomplete', prop: 'responses', value: value
this |
| Sort the array of tasks returned through the callback.
Uses the same property resolution as
For a random ordering | order_by: (o) ->
@ordering = o
this |
| Limit the array of tasks returned to
Even if one sets | limit: (l) ->
@limited = l
this |
| Run the query against the server,
then return the tasks matching all the constraints through the The | run: (callback) ->
Query.get @get_path, (err, r) =>
return callback err, r if err
tasks = r.map (t) ->
t.task
tasks = tasks.filter @check_constraints, this
if @ordering
tasks = @apply_ordering tasks
if @limited
tasks = tasks.slice 0, @limited
callback null, tasks |
Private methods | |
| Check each constraint | check_constraints: (task) ->
@constraints.every (c) ->
if c.prop of top_level
task_value = task[c.prop]
else
task_value = task.parameters[c.prop]
switch c.op
when 'ne'
task_value isnt c.value
when 'iscomplete'
complete = task_value and task_value.length
if c.value then complete else not complete
else |
| assumption that operation is | task_value is c.value |
| Apply the ordering given by | apply_ordering: (tasks) ->
if @ordering is '?'
_.shuffle tasks
else
top_level_prop = @ordering of top_level
_.sortBy tasks, (task) ->
if top_level_prop then task[@ordering] else task.parameters[@ordering]
, this
exports.Query = Query
|