Class: StoreTasks

Inherits:
Volt::Task show all
Defined in:
app/volt/tasks/store_tasks.rb

Instance Method Summary collapse

Methods inherited from Volt::Task

inherited, #initialize, known_handlers, method_missing, #timeout

Methods included from Volt::CollectionHelpers

#store, #url_for, #url_with

Constructor Details

This class inherits a constructor from Volt::Task

Instance Method Details

#dbObject



4
5
6
# File 'app/volt/tasks/store_tasks.rb', line 4

def db
  @@db ||= Volt::DataStore.fetch
end

#delete(collection, id) ⇒ Object



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'app/volt/tasks/store_tasks.rb', line 62

def delete(collection, id)
  # Load the model, then call .destroy on it
  query = nil

  Volt.skip_permissions do
    query = store.get(collection).where(id: id)
  end

  query.first.then do |model|
    if model
      if model.can_delete?
        db.delete(collection, 'id' => id)
      else
        fail "Permissions did not allow #{collection} #{id} to be deleted."
      end

      @volt_app.live_query_pool.updated_collection(collection, @channel)
    else
      fail "Could not find #{id} in #{collection}"
    end
  end
end

#load_model(collection, path, data) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'app/volt/tasks/store_tasks.rb', line 8

def load_model(collection, path, data)
  model_name = collection.singularize.camelize

  # Fetch the model
  collection = store.send(:"_#{path[-2]}")

  # See if the model has already been made
  collection.where(id: data[:id]).first.then do |model|
    # Otherwise assign to the collection
    model ||= collection

    # Create a buffer
    buffer = model.buffer

    # Assign the changed data to the buffer
    buffer.assign_attributes(data, false, true)

    buffer
  end
end

#save(collection, path, data) ⇒ Object



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
# File 'app/volt/tasks/store_tasks.rb', line 29

def save(collection, path, data)
  data = data.symbolize_keys
  promise = nil

  # Don't check the permissions when we load the model, since we want all fields
  Volt.skip_permissions do
    Volt::Model.no_validate do
      promise = load_model(collection, path, data)
    end
  end

  # On the backend, the promise is resolved before its returned, so we can
  # return from within it.
  #
  # Pass the channel as a thread-local so that we don't update the client
  # who sent the update.
  #
  # return another promise
  promise.then do |model|
    Thread.current['in_channel'] = @channel
    save_promise = model.save!.then do |result|
      next nil
    end.fail do |err|
      # An error object, convert to hash
      Promise.new.reject(err.to_h)
    end

    Thread.current['in_channel'] = nil

    next save_promise
  end
end