Skip to content

Instantly share code, notes, and snippets.

@markselby
markselby / nginx-redis-cache.lua
Created October 28, 2013 01:55
Nginx LUA script for accessing a Redis request cache
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(1000) -- 1 sec
local ok, err = red:connect("127.0.0.1", 6379)
if not ok then
ngx.log(ngx.ERR, "Redis failed to connect")
return ngx.exit(ngx.HTTP_SERVICE_UNAVAILABLE)
end
@markselby
markselby / node-express-redis-cache.js
Created October 28, 2013 02:19
Add Redis request caching to Node.js with Express.js.
var zlib = require('zlib');
var redis = require('redis');
var redisClient = redis.createClient();
var crypto = require('crypto');
// Our custom caching write function
function cached(body, lifetime, type) {
var key = this.req.originalUrl;
var res = this;
var etag, len;
@markselby
markselby / nginx-openresty-ubuntu-build-dependencies.sh
Last active July 26, 2018 08:35
Build Nginx OpenResty version on Ubuntu.This is part of the high performance caching blog on writebox.co.uk
# Build dependencies for OpenResty.
sudo apt-get install build-essential libpcre3-dev libssl-dev libgeoip-dev
# Install standard Nginx first so that you get the relevant service scripts installed too
sudo apt-get install nginx
# If you want to access Postgres via Nginx
sudo apt-get install libpq-dev
@markselby
markselby / nginx.conf
Created October 28, 2013 02:58
Nginx config for using LUA / Redis cache.
location / {
try_files $uri @redis_cache;
add_header Source Files; # Handy for development
}
location @redis_cache {
# Make sure this path is correct
# Run "nginx -V" from the command prompt and look for --prefix=/path/to/somewhere
# and place redis.lua there, or use an absolute path as shown below
content_by_lua_file /path/to/your/config/redis.lua;
@markselby
markselby / async-gists.js
Last active February 19, 2020 10:26
Load GitHub Gists asynchronously and optionally specify which file to show. This allows you to keep related files in a single gist but show them individually on your pages. The async loading prevents your page rendering from stalling.
function loadGists() {
var els = $('code[gist]'), gists = {}, code = [], stylesheets = [];
// Get elements referencing a gist and build a gists hash referencing the elements that use it
els.each(function(idx, rawEl) {
var el = $(rawEl), gist = el.attr('gist');
rawEl.gist = gist;
rawEl.file = el.attr('file');
gists[gist] = gists[gist] || { targets: [] };
gists[gist].targets.push(el);
});
@markselby
markselby / tables-accessed.sql
Last active December 27, 2015 20:49
Handy Postgres statistics queries for web development.
/*
* Find which tables were involved in a number of queries.
* This is obviously a contrived example. A practical application would be to wrap all
* the queries for a web page in a transaction (perhaps using before/after filters in
* the case of Rails) and then use the stats for cache invalidation.
*/
BEGIN TRANSACTION;
/* Run the queries */
SELECT * from news LIMIT 5;
@markselby
markselby / create-sitemap.sh
Last active January 1, 2016 09:09
Fast sitemap.xml generation using Postgres.
#/bin/sh
(
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?><urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">"
psql -c "COPY (SELECT xmlelement(name url, xmlforest('http://writebox.co.uk/news/' || slug AS loc, to_char(updated_at, 'YYYY-MM-DDThh:mm:ss+07:00') AS lastmod)) FROM news) TO STDOUT" writebox_$2
echo "</urlset>"
) > $1/public/sitemap.xml
cat $1/public/sitemap.xml | gzip -9 > $1/public/sitemap.xml.gz
@markselby
markselby / plv8-base.sql
Last active January 2, 2016 01:59
Simplify everything with Postgres and Javascript - PL/v8
-- eg SELECT sort_order('-relevance', ['title', 'updated_at', 'relevance'])
-- Optionally specify +/- prefix for sort field. Invalid sort field uses first in array
CREATE OR REPLACE FUNCTION sort_order(_field text, _valid text[]) RETURNS json AS
$$
_field = decodeURIComponent(_field);
var directions = { ' ': 'ASC', '-': 'DESC' }; // + becomes space
var direction = directions[_field[0]];
if(direction) { _field = _field.slice(1) } else { direction = directions['-']; };
if(_valid.indexOf(_field) < 0) _field = _valid[0];
return { field: _field, direction: direction };
@markselby
markselby / after-jquery.js
Last active August 29, 2015 13:57
Running Javascript after render.
// Somewhere in your javascript assets included at the end of the document
$(document).ready(function() {
loaded = true;
doInit();
});
@markselby
markselby / command-line
Created March 20, 2014 03:05
Simplified Postgres database pool access for Node.js
NODE_ENV=development node sample-usage.js