Skip to content

Commit d22f164

Browse files
committed
Added create event api route
1 parent 6f8e64d commit d22f164

4 files changed

Lines changed: 61 additions & 0 deletions

File tree

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# frozen_string_literal: true
2+
3+
module Api
4+
class EventsController < ApiController
5+
before_action :authorize_user
6+
7+
def create
8+
event = Event.new(event_params.merge(user_id: current_user.id, time: Time.current))
9+
if event.save
10+
head :created
11+
else
12+
render json: { error: event.errors }, status: :bad_request
13+
end
14+
end
15+
16+
private
17+
18+
def event_params
19+
params.expect(event: [:name, { properties: {} }])
20+
end
21+
end
22+
end

app/models/event.rb

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
11
# frozen_string_literal: true
22

33
class Event < ApplicationRecord
4+
validates :name, presence: true
5+
validates :time, presence: true
6+
validates :user_id, presence: true
47
end

config/routes.rb

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,8 @@
105105

106106
get '/join/:join_code', to: 'join#show'
107107
post '/join/:join_code', to: 'join#create'
108+
109+
resources :events, only: %i[create]
108110
end
109111

110112
resource :github_webhooks, only: :create, defaults: { formats: :json }
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# frozen_string_literal: true
2+
3+
require 'rails_helper'
4+
5+
RSpec.describe 'Create events', type: :request do
6+
let(:headers) { { Authorization: UserProfileMock::TOKEN } }
7+
let(:user) { create(:user) }
8+
9+
before do
10+
authenticated_in_hydra_as(user)
11+
end
12+
13+
it('posting event returns created status') do
14+
post('/api/events', headers:, params: { event: { name: 'Test Event', properties: { key: 'value' } } })
15+
expect(response).to have_http_status(:created)
16+
end
17+
18+
it('creating an event without a name returns bad request') do
19+
post('/api/events', headers:, params: { event: { properties: { key: 'value' } } })
20+
expect(response).to have_http_status(:bad_request)
21+
end
22+
23+
it('created event is stored in the database with correct attributes') do
24+
post('/api/events', headers:, params: { event: { name: 'Test Event', properties: { key: 'value' } } })
25+
event = Event.last
26+
expect(event.name).to eq('Test Event')
27+
expect(event.properties).to eq({ 'key' => 'value' })
28+
end
29+
30+
it('creating an event without authentication returns unauthorized') do
31+
post('/api/events', params: { event: { name: 'Test Event', properties: { key: 'value' } } })
32+
expect(response).to have_http_status(:unauthorized)
33+
end
34+
end

0 commit comments

Comments
 (0)