Cap sensor readings to 5,000 count

sensor_reading_limits
Rick Carlino 2020-02-13 13:10:48 -06:00
parent 6c3e60999c
commit 2a6fe06ba3
2 changed files with 36 additions and 5 deletions

View File

@ -1,7 +1,10 @@
module Api
class SensorReadingsController < Api::AbstractController
LIMIT = 5000
before_action :clean_old
def create
mutate SensorReadings::Create.run(raw_json, device: current_device)
mutate SensorReadings::Create.run(raw_json, device: current_device)
end
def index
@ -17,10 +20,23 @@ module Api
render json: ""
end
private
private
def clean_old
if current_device.sensor_readings.count > LIMIT
current_device
.sensor_readings
.where
.not(id: readings.pluck(:id))
.delete_all
end
end
def readings
SensorReading.where(device: current_device)
@readings ||= SensorReading
.where(device: current_device)
.order(created_at: :desc)
.limit(LIMIT)
end
def reading

View File

@ -18,7 +18,7 @@ describe Api::SensorReadingsController do
x: nil,
y: 1,
z: 2,
mode: 1
mode: 1,
}.to_json,
params: { format: :json }
@ -40,7 +40,7 @@ describe Api::SensorReadingsController do
y: 1,
z: 2,
mode: 1,
read_at: read_at
read_at: read_at,
}.to_json,
params: { format: :json }
@ -105,5 +105,20 @@ describe Api::SensorReadingsController do
post :create, body: {}.to_json
expect(response.status).to eq(401)
end
it "cleans up excess logs" do
const_reassign(Api::SensorReadingsController, :LIMIT, 5)
sign_in user
10.times do |n|
FactoryBot.create(:sensor_reading,
device: user.device,
created_at: n.minutes.ago)
end
expect(user.device.sensor_readings.count).to eq(10)
get :index, params: { format: :json }
expect(json.count).to eq(5)
expect(user.device.sensor_readings.count).to eq(5)
const_reassign(Api::SensorReadingsController, :LIMIT, 5000)
end
end
end