Using Firestore in a Sinatra Web App

ciscovlahakis

Cisco Vlahakis

Posted on November 19, 2023

Using Firestore in a Sinatra Web App

Firestore is a NoSql DB created by Google that allows for simple querying. Data is stored as documents within collections. For example, "restaurants" can be a collection and "McDonald's" can be a document with id "mcdonaldsid" and name "McDonald's". To install Firestore, run

gem 'google-cloud-firestore'
Enter fullscreen mode Exit fullscreen mode

and make sure to add

'google-cloud-firestore'
Enter fullscreen mode Exit fullscreen mode

to your Gemfile. Then, to use Firestore in an erb file, require it and create a firestore object which takes your project_id and credentials. Remember that your credentials file is the entire JSON object while project_id is one field within that object. You can find this JSON object in your Firestore settings:

require 'google/cloud/firestore'

firestore = Google::Cloud::Firestore.new(
    project_id: 'your-project-id',
    credentials: '/path/to/your/credentials/file.json'
)
Enter fullscreen mode Exit fullscreen mode

and the entire JSON object, which you can put in a file called initialize_firestore.erb:

require 'google/cloud/firestore'

firestore = Google::Cloud::Firestore.new({
  :project_id => ENV.fetch('GOOGLE_PROJECT_ID'),
  :credentials => {
    :type => ENV.fetch('GOOGLE_TYPE'),
    :project_id => ENV.fetch('GOOGLE_PROJECT_ID'),
    :private_key_id => ENV.fetch('GOOGLE_PRIVATE_KEY_ID'),
    :private_key => ENV.fetch('GOOGLE_PRIVATE_KEY'),
    :client_email => ENV.fetch('GOOGLE_CLIENT_EMAIL'),
    :client_id => ENV.fetch('GOOGLE_CLIENT_ID'),
    :auth_uri => ENV.fetch('GOOGLE_AUTH_URI'),
    :token_uri => ENV.fetch('GOOGLE_TOKEN_URI'),
    :auth_provider_x509_cert_url => ENV.fetch('GOOGLE_AUTH_PROVIDER_X509_CERT_URL'),
    :client_x509_cert_url => ENV.fetch('GOOGLE_CLIENT_X509_CERT_URL')
  }
})
Enter fullscreen mode Exit fullscreen mode

Now onto the fun! In the example below, we are referencing a document holding info for "frank" in the "users" collection:

doc_ref = firestore.doc "users/frank"
Enter fullscreen mode Exit fullscreen mode

Then, we get the contents, which holds metadata like id and the actual data:

doc_snapshot = doc_ref.get
puts "Document data: #{doc_snapshot.data}."
Enter fullscreen mode Exit fullscreen mode

You can also get all documents in a collection, create a snapshot on a collection that fires when documents are added, edited, or deleted, filter data, and much more!

💖 💪 🙅 🚩
ciscovlahakis
Cisco Vlahakis

Posted on November 19, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related