Skip to content

Instantly share code, notes, and snippets.

@distributedlife
Created February 6, 2017 00:06
Show Gist options
  • Save distributedlife/38525aaa24e739ec42a873bfacfe1082 to your computer and use it in GitHub Desktop.
Save distributedlife/38525aaa24e739ec42a873bfacfe1082 to your computer and use it in GitHub Desktop.
An example of a lambda using claudia.js
const ApiBuilder = require('claudia-api-builder');
const api = new ApiBuilder();
const cheerio = require('cheerio')
const fetch = require('node-fetch')
const text = (element) => element.text().trim()
const numbers = (text) => text.match(/^([0-9]+)/g)
const count = (text) => (numbers(text) && numbers(text)[0]) || 0
const followers = (text) => numbers(text)[0] || 0
const following = (text) => numbers(text)[1] || 0
const base = 'https://goodfil.ms';
const profileUrl = (id) => `${base}/${id}`
const getProfileForId = (id) => {
'use strict';
const mapProfile = ($) => ({
background: $('div.stats img').attr('src'),
avatar: $('div.stats img').attr('src'),
id: id,
name: text($('div.stats div.name')),
counts: {
reviews: count(text($(`a[href="/${id}/reviews"]`))),
ratings: count(text($(`a[href="/${id}/ratings"]`))),
queued: count(text($(`a[href="/${id}/queue"]`))),
lists: count(text($(`a[href="/${id}/lists"]`))),
followers: followers(text($(`a[href="/${id}/people"]`))),
following: following(text($(`a[href="/${id}/people"]`))),
},
})
return fetch(profileUrl(id))
.then((resp) => resp.text())
.then((body) => cheerio.load(body))
.then(mapProfile)
}
api.get('/profile/{id}', (request) => {
'use strict';
const id = request.pathParams.id;
return getProfileForId(id).catch((error) => { error });
})
module.exports = api;
{
"name": "sample-api",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"deploy": "claudia update --profile claudia"
},
"author": "Ryan Boucher",
"license": "ISC",
"dependencies": {
"aws-serverless-express": "^1.2.0",
"cheerio": "^0.22.0",
"claudia": "^2.4.0",
"claudia-api-builder": "^2.3.1",
"express": "^4.14.0",
"node-fetch": "^1.6.3"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment