Module: Strelka::App::RestResources::ClassMethods

Includes:
Sequel::Inflections, Constants
Defined in:
lib/strelka/app/restresources.rb

Overview

Class methods to add to classes with REST resources.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#resource_verbsObject (readonly)

The list of REST routes assigned to Sequel::Model objects



95
96
97
# File 'lib/strelka/app/restresources.rb', line 95

def resource_verbs
  @resource_verbs
end

#service_optionsObject (readonly)

The global service options hash



98
99
100
# File 'lib/strelka/app/restresources.rb', line 98

def service_options
  @service_options
end

Class Method Details

.extended(obj) ⇒ Object

Extension callback -- overridden to also install dependencies.



102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/strelka/app/restresources.rb', line 102

def self::extended( obj )
	super

	# Enable text tables for text/plain responses
	Sequel.extension( :pretty_table )

	# Load the plugins this one depends on if they aren't already
	obj.plugins :routing, :negotiation, :parameters

	# Use the 'exclusive' router instead of the more-flexible
	# Mongrel2-style default one
	obj.router :exclusive
end

Instance Method Details

#add_collection_create_handler(route, rsrcobj, options) ⇒ Object

Add a handler method for creating a new instance of rsrcobj. POST /resources



290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
# File 'lib/strelka/app/restresources.rb', line 290

def add_collection_create_handler( route, rsrcobj, options )
	self.log.debug "Creating handler for creating %p resources: POST %s" %
		[ rsrcobj, route ]

	self.add_route( :POST, route, options ) do |req|
		add_resource_params( req.params, rsrcobj )
		finish_with( HTTP::BAD_REQUEST, req.params.error_messages.join(", ") ) unless
			req.params.okay?

		resource = rsrcobj.new( req.params.valid )

		# Save it in a transaction, erroring if any validations fail
		begin
			resource.save
		rescue Sequel::ValidationFailed => err
			finish_with( HTTP::BAD_REQUEST, err.message )
		end

		# :TODO: Eventually, this should be factored out into the Sequel plugin
		resuri = [ req.base_uri, route, resource.pk ].join( '/' )

		res = req.response
		res.status = HTTP::CREATED
		res.headers.location = resuri
		res.headers.content_location = resuri

		res.for( :json, :yaml ) { resource }

		return res
	end

	self.resource_verbs[ route ] << :POST
end

#add_collection_deletion_handler(route, rsrcobj, options) ⇒ Object

Add a handler method for deleting all instances of rsrcobj collection with route as the base URI path. DELETE /resources



484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
# File 'lib/strelka/app/restresources.rb', line 484

def add_collection_deletion_handler( route, rsrcobj, options )
	pkey = rsrcobj.primary_key
	self.log.debug "Creating handler for deleting every %p resources: DELETE %s" %
		[ rsrcobj, route ]

	self.add_route( :DELETE, route, options ) do |req|
		self.log.debug "Deleting all %p objects" % [ rsrcobj ]

		# Save it in a transaction, erroring if any of 'em fail validations
		begin
			rsrcobj.db.transaction do
				rsrcobj.each {|obj| obj.destroy }
			end
		rescue Sequel::Error => err
			finish_with( HTTP::BAD_REQUEST, err.message )
		end

		res = req.response
		res.status = HTTP::NO_CONTENT

		return res
	end

	self.resource_verbs[ route ] << :DELETE
end

#add_collection_read_handler(route, rsrcobj, options) ⇒ Object

Add a handler method for reading a collection of the specified rsrcobj, which should be a Sequel::Model class or a ducktype-alike. GET /resources



245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
# File 'lib/strelka/app/restresources.rb', line 245

def add_collection_read_handler( route, rsrcobj, options )
	self.log.debug "Creating handler for reading collections of %p: GET %s" %
		[ rsrcobj, route ]

	# Make a column regexp for validating the order field
	colunion = Regexp.union( rsrcobj.columns.map(&:to_s) )
	colre = /^(?<column>#{colunion})$/

	self.add_route( :GET, route, options ) do |req|
		# Add validations for limit, offset, and order parameters
		req.params.add :limit, :integer
		req.params.add :offset, :integer
		req.params.add :order, colre, :multiple

		finish_with( HTTP::BAD_REQUEST, req.params.error_messages.join("\n") ) unless
			req.params.okay?

		limit, offset, order = req.params.values_at( :limit, :offset, :order )
		res = req.response

		dataset = rsrcobj.dataset
		if order
			order = Array( order ).map( &:to_sym )
			self.log.debug "Ordering result set by %p" % [ order ]
			dataset = dataset.order( *order )
		end

		if limit
			self.log.debug "Limiting result set to %p records" % [ limit ]
			dataset = dataset.limit( limit, offset )
		end

		self.log.debug "Returning collection: %s" % [ dataset.sql ]
		res.for( :json, :yaml ) { dataset.all }
		res.for( :text ) { Sequel::PrettyTable.string(dataset) }

		return res
	end

	self.resource_verbs[ route ] << :GET << :HEAD
end

#add_collection_replace_handler(route, rsrcobj, options) ⇒ Object

Add a handler method for replacing all instances of rsrcobj collection. PUT /resources



403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
# File 'lib/strelka/app/restresources.rb', line 403

def add_collection_replace_handler( route, rsrcobj, options )
	pkey = rsrcobj.primary_key
	self.log.debug "Creating handler for replacing all %p resources: PUT %s" %
		[ rsrcobj, route ]

	self.add_route( :PUT, route, options ) do |req|

		# Make a validator that can be reused to validate each resource's attributes
		validator = self.class.paramvalidator.dup
		add_resource_params( validator, rsrcobj )
		body = req.parse_body
		body = [ body ] unless body.is_a?( Array )

		# Create resource objects out of the incoming data
		new_resources = []
		body.each do |attributes|
			validator.validate( attributes )
			finish_with( HTTP::BAD_REQUEST, validator.error_messages.join(", ") ) unless
				validator.okay?

			new_resources << rsrcobj.new( validator.valid )
		end
		self.log.debug "Replacing %p collection with new values: %p" %
			[ rsrcobj, new_resources ]

		# Save it in a transaction, erroring if any of 'em fail validations
		begin
			rsrcobj.db.transaction do
				rsrcobj.truncate
				new_resources.each( &:save )
			end
		rescue Sequel::ValidationFailed => err
			finish_with( HTTP::BAD_REQUEST, err.message )
		end

		res = req.response
		res.status = HTTP::NO_CONTENT

		return res
	end

	self.resource_verbs[ route ] << :PUT
end

#add_composite_read_handler(path, rsrcobj, association, options) ⇒ Object

Add a GET route for the specified association of the rsrcobj at the given path.



610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
# File 'lib/strelka/app/restresources.rb', line 610

def add_composite_read_handler( path, rsrcobj, association, options )
	self.log.debug "Adding composite read handler for association: %s" % [ association ]

	pkey = rsrcobj.primary_key
	colunion = Regexp.union( rsrcobj.columns.map(&:to_s) )
	colre = /^(?<column>#{colunion})$/

	self.add_route( :GET, path, options ) do |req|

		# Add validations for limit, offset, and order parameters
		req.params.add :limit, :integer
		req.params.add :offset, :integer
		req.params.add :order, colre
		finish_with( HTTP::BAD_REQUEST, req.params.error_messages.join("\n") ) unless
			req.params.okay?

		# Fetch the primary key from the parameters
		res = req.response
		id = req.params[ pkey ]

		# Look up the resource, and if it exists, use it to fetch its associated
		# objects
		resource = rsrcobj[ id ] or
			finish_with( HTTP::NOT_FOUND, "No such %s [%p]" % [rsrcobj.table_name, id] )

		limit, offset, order = req.params.values_at( :limit, :offset, :order )
		dataset = resource.send( "#{association}_dataset" )

		# Apply the order parameter if it exists
		if order
			order = Array( order ).map( &:to_sym )
			self.log.debug "Ordering result set by %p" % [ order ]
			dataset = dataset.order( *order )
		end

		# Apply limit and offset parameters if they exist
		if limit
			self.log.debug "Limiting result set to %p records" % [ limit ]
			dataset = dataset.limit( limit, offset )
		end

		# Fetch and return the records as JSON or YAML
		# :TODO: Handle other mediatypes
		self.log.debug "Returning collection: %s" % [ dataset.sql ]
		res.for( :json, :yaml ) { dataset.all }
		res.for( :text ) { Sequel::PrettyTable.string(dataset) }

		return res
	end
end

#add_composite_resource_handlers(route_prefix, rsrcobj, options) ⇒ Object

Add routes for any associations rsrcobj has as composite resources.



512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
# File 'lib/strelka/app/restresources.rb', line 512

def add_composite_resource_handlers( route_prefix, rsrcobj, options )
	self.log.debug "Adding composite resource handlers for %p to %s (%p)" %
		[ rsrcobj, route_prefix, options ]

	# Add methods declared by (user-declared) dataset modules.
	ds_mods = rsrcobj.dataset_method_modules.select do |mod|
		mod.is_a?( Sequel::Model::DatasetModule ) || mod.name.nil?
	end.each

	ds_mods.each do |mod|
		self.log.debug "  adding dataset methods declared by %p" % [ mod ]
		self.add_dataset_module_routes( route_prefix, rsrcobj, mod, options )
	end

	# Add composite service routes for each association
	self.log.debug "Adding composite resource routes for %p" % [ rsrcobj ]
	rsrcobj.association_reflections.each do |name, refl|
		pkey = rsrcobj.primary_key
		route = "%s/:%s/%s" % [ route_prefix, pkey, name ]
		self.log.debug "  route for associated %p objects via the %s association: %s" %
			[ refl[:class_name], name, route ]
		self.add_composite_read_handler( route, rsrcobj, name, options )
	end

end

#add_dataset_module_routes(route_prefix, rsrcobj, mod, options) ⇒ Object

Add routes for the methods declared in the dataset module mod.



540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
# File 'lib/strelka/app/restresources.rb', line 540

def add_dataset_module_routes( route_prefix, rsrcobj, mod, options )
	self.log.debug "Adding dataset module routes."

	mod.instance_methods.each do |methname|
		meth = mod.instance_method( methname )
		self.log.debug "    instance_method: %p" % [ meth ]

		route  = "%s/%s" % [ route_prefix, methname ]
		params = []

		# Add a route placeholder for each parameter of the dataset method
		meth.parameters.each do |type, param|
			self.log.debug "    adding parameter placeholder to the route for %s parameter %p" %
				[ type, param ]
			route  << "/:%s" % [ param ]
			params << param
		end

		self.log.debug "  route for dataset method %s: %s" % [ methname, route ]
		self.add_dataset_read_handler( route, rsrcobj, methname, params, options )
	end

	self.log.debug "  done with dataset module routes."
end

#add_dataset_read_handler(path, rsrcobj, dsname, params, options) ⇒ Object

Add a GET route for the dataset method dsname for the given rsrcobj at the given path.



568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
# File 'lib/strelka/app/restresources.rb', line 568

def add_dataset_read_handler( path, rsrcobj, dsname, params, options )
	self.log.debug "Adding dataset method read handler: %s" % [ path ]

	# Only need to declare a parameter if the dataset method has one
	params.each do |paramname|
		config = rsrcobj.db_schema[ paramname ] or
			raise ArgumentError, "no such column %p for %p" % [ paramname, rsrcobj ]
		param( paramname, config[:type] )
	end

	self.add_route( :GET, path, options ) do |req|
		self.log.debug "Resource dataset GET request for dataset %s on %p" %
			[ dsname, rsrcobj ]
		finish_with( HTTP::BAD_REQUEST, req.params.error_messages.join("\n") ) unless
			req.params.okay?

		# Get the dataset, either with a parameter or without one
		args    = req.params.values_at( *params )
		dataset = rsrcobj.send( dsname, *args )
		self.log.debug "  dataset is: %p" % [ dataset ]

		# Apply offset and limit if they're present
		limit, offset = req.params.values_at( :limit, :offset )
		if limit
			self.log.debug "  limiting result set to %p records" % [ limit ]
			dataset = dataset.limit( limit, offset )
		end

		# Fetch and return the records as JSON or YAML
		# :TODO: Handle other mediatypes
		self.log.debug "  returning collection: %s" % [ dataset.sql ]
		res = req.response
		res.for( :json, :yaml ) { dataset.all }
		res.for( :text ) { Sequel::PrettyTable.string(dataset) }

		return res
	end
end

#add_delete_handler(route_prefix, rsrcobj, options) ⇒ Object

Add a handler method for deleting an instance of rsrcobj with route_prefix as the base URI path. DELETE /resources/id



451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
# File 'lib/strelka/app/restresources.rb', line 451

def add_delete_handler( route_prefix, rsrcobj, options )
	pkey = rsrcobj.primary_key
	route = "#{route_prefix}/:#{pkey}"

	self.add_route( :DELETE, route, options ) do |req|
		finish_with( HTTP::BAD_REQUEST, req.params.error_messages.join(", ") ) unless
			req.params.okay?

		id = req.params[ pkey ]

		if resource = rsrcobj[ id ]
			self.log.debug "Deleting %p [%p]" % [ resource.class, id ]

			begin
				resource.destroy
			rescue Sequel::Error => err
				finish_with( HTTP::BAD_REQUEST, err.message )
			end
		end

		res = req.response
		res.status = HTTP::NO_CONTENT

		return res
	end

	self.resource_verbs[ route_prefix ] << :DELETE
end

#add_options_handler(route, rsrcobj, options) ⇒ Object

Add a handler method for discovery for the specified rsrcobj. OPTIONS /resources



181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
# File 'lib/strelka/app/restresources.rb', line 181

def add_options_handler( route, rsrcobj, options )
	# :TODO: Documentation for HTML mode (possibly using http://swagger.wordnik.com/)
	self.log.debug "Adding OPTIONS handler for %s (%p)" % [ route, rsrcobj ]
	self.add_route( :OPTIONS, route, options ) do |req|
		self.log.debug "OPTIONS handler!"
		res = req.response

		# Gather up metadata describing the resource
		verbs = self.class.resource_verbs[ route ].sort
		columns = rsrcobj.columns
		attributes = columns.each_with_object({}) do |col, hash|
			hash[ col ] = rsrcobj.db_schema[ col ][:type]
		end

		self.log.debug "  making a reply with Allowed: %s" % [ verbs.join(', ') ]
		res.header.allowed = verbs.join(', ')
		res.for( :json, :yaml ) do |req|
			{
				'methods' => verbs,
				'attributes' => attributes,
			}
		end
		res.for( :text ) do
			"Methods: #{verbs.join(', ')}\n" +
			"Attributes: \n" +
			attributes.map {|name,type| "  "}
		end

		return res
	end

	self.resource_verbs[ route ] << :OPTIONS
end

#add_read_handler(route_prefix, rsrcobj, options) ⇒ Object

Add a handler method for reading a single instance of the specified rsrcobj, which should be a Sequel::Model class or a ducktype-alike. GET /resources/id



218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
# File 'lib/strelka/app/restresources.rb', line 218

def add_read_handler( route_prefix, rsrcobj, options )
	pkey = rsrcobj.primary_key
	route = "#{route_prefix}/:#{pkey}"

	self.log.debug "Creating handler for reading a single %p: GET %s" % [ rsrcobj, route ]
	self.add_route( :GET, route, options ) do |req|
		finish_with( HTTP::BAD_REQUEST, req.params.error_messages.join("\n") ) unless
			req.params.okay?

		id = req.params[ pkey ]
		resource = rsrcobj[ id ] or
			finish_with( HTTP::NOT_FOUND, "No such %s [%p]" % [rsrcobj.table_name, id] )

		res = req.response
		res.for( :json, :yaml ) { resource }
		res.for( :text ) { Sequel::PrettyTable.string(resource) }

		return res
	end

	self.resource_verbs[ route_prefix ] << :GET << :HEAD
end

#add_replace_handler(route_prefix, rsrcobj, options) ⇒ Object

Add a handler method for replacing an instance of rsrcobj. PUT /resources/id



364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
# File 'lib/strelka/app/restresources.rb', line 364

def add_replace_handler( route_prefix, rsrcobj, options )
	pkey = rsrcobj.primary_key
	route = "#{route_prefix}/:#{pkey}"

	self.log.debug "Creating handler for replacing %p a resource: PUT %s" %
		[ rsrcobj, route ]
	self.add_route( :PUT, route, options ) do |req|
		add_resource_params( req.params, rsrcobj )
		finish_with( HTTP::BAD_REQUEST, req.params.error_messages.join(", ") ) unless
			req.params.okay?

		id = req.params[ pkey ]
		resource = rsrcobj[ id ] or
			finish_with( HTTP::NOT_FOUND, "no such %s [%p]" % [ rsrcobj.name, id ] )

		newvals = req.params.valid
		self.log.debug "Replacing %p: %p" % [ resource, newvals ]

		begin
			resource.values.clear
			resource[ pkey ] = newvals.delete( pkey.to_sym )
			resource.set( newvals )
			resource.save
		rescue Sequel::Error => err
			finish_with( HTTP::BAD_REQUEST, err.message )
		end

		res = req.response
		res.status = HTTP::NO_CONTENT

		return res
	end

	self.resource_verbs[ route_prefix ] << :PUT
end

#add_update_handler(route_prefix, rsrcobj, options) ⇒ Object

Add a handler method for updating an instance of rsrcobj. POST /resources/id



327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
# File 'lib/strelka/app/restresources.rb', line 327

def add_update_handler( route_prefix, rsrcobj, options )
	pkey = rsrcobj.primary_key
	route = "#{route_prefix}/:#{pkey}"

	self.log.debug "Creating handler for updating a single %p resource: POST %s" %
		[ rsrcobj, route ]
	self.add_route( :POST, route, options ) do |req|
		add_resource_params( req.params, rsrcobj )
		finish_with( HTTP::BAD_REQUEST, req.params.error_messages.join(", ") ) unless
			req.params.okay?

		id = req.params[ pkey ]
		resource = rsrcobj[ id ] or
			finish_with( HTTP::NOT_FOUND, "no such %s [%p]" % [ rsrcobj.name, id ] )

		newvals = req.params.valid
		newvals.delete( pkey.to_sym )
		self.log.debug "Updating %p with new values: %p" % [ resource, newvals ]

		begin
			resource.update( newvals )
		rescue Sequel::Error => err
			finish_with( HTTP::BAD_REQUEST, err.message )
		end

		res = req.response
		res.status = HTTP::NO_CONTENT

		return res
	end

	self.resource_verbs[ route_prefix ] << :POST
end

#inherited(subclass) ⇒ Object

Inheritance callback -- copy plugin data to inheriting subclasses.



118
119
120
121
122
123
124
125
126
# File 'lib/strelka/app/restresources.rb', line 118

def inherited( subclass )
	super

	verbs_copy = Strelka::DataUtilities.deep_copy( self.resource_verbs )
	subclass.instance_variable_set( :@resource_verbs, verbs_copy )

	opts_copy = Strelka::DataUtilities.deep_copy( self.service_options )
	subclass.instance_variable_set( :@service_options, opts_copy )
end

#resource(rsrcobj, options = {}) ⇒ Object

Expose the specified rsrcobj (which should be an object that responds to #dataset and returns a Sequel::Dataset)



137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# File 'lib/strelka/app/restresources.rb', line 137

def resource( rsrcobj, options={} )
	self.log.debug "Adding REST resource for %p" % [ rsrcobj ]
	options = self.service_options.merge( options )
	self.log.warn "Options = %p" % [ options ]

	# Add a parameter for the primary key
	pkey = rsrcobj.primary_key
	pkey_schema = rsrcobj.db_schema[ pkey.to_sym ] or
		raise ArgumentError,
			"cannot generate services for %p: resource has no schema" % [ rsrcobj ]
	self.param( pkey, pkey_schema[:type] ) unless
		self.paramvalidator.param_names.include?( pkey.to_s )

	# Figure out what the resource name is, and make the route from it
	name = options[:name] || rsrcobj.implicit_table_name
	route = [ options[:prefix], name ].compact.join( '/' )
	self.log.warn "Route is: %p" % [[ options[:prefix], name ]]

	# Make and install handler methods
	self.log.debug "  adding readers"
	self.add_options_handler( route, rsrcobj, options )
	self.add_read_handler( route, rsrcobj, options )
	self.add_collection_read_handler( route, rsrcobj, options )

	# Add handler methods for the mutator parts of the API unless
	# the resource is read-only
	if options[:readonly]
		self.log.debug "  skipping mutators (read-only set)"
	else
		self.add_collection_create_handler( route, rsrcobj, options )
		self.add_update_handler( route, rsrcobj, options )
		self.add_collection_replace_handler( route, rsrcobj, options )
		self.add_replace_handler( route, rsrcobj, options )
		self.add_collection_deletion_handler( route, rsrcobj, options )
		self.add_delete_handler( route, rsrcobj, options )
	end

	# Add any composite resources based on the +rsrcobj+'s associations
	self.add_composite_resource_handlers( route, rsrcobj, options ) if options[:composite]
end

#resource_prefix(route) ⇒ Object

Set the prefix for all following resource routes to route.



130
131
132
# File 'lib/strelka/app/restresources.rb', line 130

def resource_prefix( route )
	self.service_options[ :prefix ] = route
end