adding likes to friendwave.me
you can like logs and posts on friendwave.me, which is kind of cool. but it’s a static (jekyll) site so how?
well the first thing you need is somewhere to store them. i found dbhub.io which provides SQLite hosting and an API to read from and write to your databases.
i wouldn’t want to expose my API keys though so i need to put the actual API calls behind something. this site is hosted on vercel which provides serverless functions. you can just create an /api
directory in your jekyll site, write some functions in there and suddenly your static site has a backend.
if you go to https://friendwave.me/api/likes for example you can see some likes data.
“but friendwave,” you say, “i haven’t authenticated in any way. how can you differentiate between different users?” i can’t. which means you can smash that like as many times as you want. (please smash that like).
anyway here’s some code:
# dhub.rb
# code for making requests to the dbhub API
require 'net/http'
require 'uri'
require 'base64'
def send_request(api_type:, query:, db_name:)
encoded_query = Base64.encode64(query)
uri = URI.parse("https://api.dbhub.io/v1/#{api_type}")
request = Net::HTTP::Post.new(uri)
request.set_form_data({
'apikey' => ENV['dbhub_api_key']
'dbowner' => ENV['dbhub_db_owner']
'dbname' => db_name,
'sql' => encoded_query
})
Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http| http.request(request) }
end
# likes.rb
# fetching all likes
# should probably fetch only the likes i need
# on a given page but this will do for now
require_relative 'dbhub'
Handler = Proc.new do |request, response|
query = "SELECT likeable_id, COUNT(*) FROM likes GROUP BY likeable_id;"
api_response = send_request(api_type: 'query', query: query, db_name: ENV['dbhub_db_name'])
response.status = 200
response['Content-Type'] = 'application/json; charset=utf-8'
response['Access-Control-Allow-Origin'] = '*'
response.body = JSON.parse(api_response.body).map do |row|
{
likeable_id: row[0]["Value"],
likes_count: row[1]["Value"].to_i
}
end.to_json
end
# like.rb
# when you smash that like
require_relative 'dbhub'
Handler = proc do |request, response|
likeable_id = request.query['id']
query = "INSERT INTO likes (likeable_id, created_at) VALUES (#{likeable_id}, datetime('now'));"
send_request(api_type: 'execute', query: query, db_name: ENV['dbhub_db_name'])
response['Access-Control-Allow-Origin'] = '*'
response.status = 200
end