contentful / contentful_model

A lightweight wrapper around the Contentful api gem, to make it behave more like ActiveRecord
MIT License
44 stars 42 forks source link

find! and first! #136

Closed fsubal closed 4 years ago

fsubal commented 5 years ago

Issue type

Feature request

Example Problem

Currently I'm using contentful_model + Rails, and caching our view template so that it prevents too many request to Contentful API.

= cache [@slug, ...], expires_in: 5.minute do
  // Doing inside cache!
  // Otherwise, our controller would request to contentful for every page view
  - content = @contentful_model_query.first
  div
    = content.name

Our content could be nil. I want to make this case 404 Not Found.

As a workaround, I'm doing this.

= cache [@slug, ...], expires_in: 5.minute do
  - unless content = @contentful_model_query.first
    - raise ::MyContentController::ContentNotFound
class MyContentController < ApplicationController
  class ContentNotFound < StandardError; end

  rescue_from ContentNotFound, with: -> { head :not_found }

  before_action :set_content_model_query

  def set_content_model_query
    @contentful_model_query ||= MyContent.load_childen(...).where(slug: params[:slug])
  end
end

This works, but I'd like a more handy way.

Feature Request

How about ContentfulModel::Query have .first! along with .first ( And find! for find too ).

Raising a custom error makes handling with empty responses in handier way.

fsubal commented 4 years ago

I think this is solved by #138 ?