Snippets

Fantom-Factory Internet Chuck Norris Database Client

Created by Steve Eynon last modified

Fantom meets Chuck Norris

Fantom meets Chuck Norris

This is a mini API that lets you retrieve jokes from the Internet Chuck Norris Database.

Sample usage:

class Example {
    Void main() {
        client := IcndbClient()
        echo(client.noOfJokes)    // --> 546
        echo(client.categories)   // --> [explicit, nerdy]
        echo(client.random.joke)  // --> Love does not hurt. Chuck Norris does.
        echo(client[461].joke)    // --> Chuck Norris finished World of Warcraft.

        echo(IcndbClient("Emma", "Statham") { it.limitTo.add("nerdy") }.random.joke)
        // --> Emma Statham can install a 64 bit OS on 32 bit machines.
    }
}

See the Fantom meets Chuck Norris Article on Alien-Factory for details.

using util
using web

** The Internet Chuck Norris Database Client
class IcndbClient {
	private Uri icndbUrl := `http://api.icndb.com/`

	Str?  firstName
	Str?  lastName
	Str[] limitTo := [,]
	Str[] exclude := [,]
	
	new makeWithName(Str? firstName := null, Str? lastName := null) {
		this.firstName = firstName
		this.lastName  = lastName
	}
	
	@Operator
	Joke get(Int id) {
		Joke(fetch(`jokes/${id}`, true))
	}
	
	Joke random() {
		Joke(fetch(`jokes/random`, true))
	}

	Str[] categories() {
		fetch(`categories`, false)
	}
	
	Int noOfJokes() {
		fetch(`jokes/count`, false)
	}
	
	private Obj fetch(Uri url, Bool addQuery) {
		if (addQuery) {
			query := ["escape":"javascript"]
			if (firstName != null) query["firstName"] = firstName
			if (lastName  != null) query["lastName"]  = lastName
			if (!limitTo.isEmpty)  query["limitTo"]   = limitTo.toStr
			if (!exclude.isEmpty)  query["exclude"]   = exclude.toStr
			url = url.plusQuery(query)
		}

		json := WebClient(icndbUrl + url).getStr.replace("\\'", "'")
		try {
			data := (Str:Obj?) JsonInStream(json.in).readJson
			return data["value"]
			
		} catch (ParseErr err) {
			msg := json.replace("<br />", "").replace("<b>", "").replace("</b>", "").replace("\n\n", "\n")
			throw ParseErr(msg)
		}
	}	
}

const class Joke {
	const Int   id
	const Str   joke
	const Str[] categories
	
	internal new make(Str:Obj? data) {
		this.id		 = data["id"]
		this.joke	   = data["joke"]
		this.categories = data["categories"]
	}
}

Comments (0)