Skip to content

Instantly share code, notes, and snippets.

@tomasklapka
Last active August 29, 2015 14:09
Show Gist options
  • Save tomasklapka/60662d46863fa39e4379 to your computer and use it in GitHub Desktop.
Save tomasklapka/60662d46863fa39e4379 to your computer and use it in GitHub Desktop.
Request and parse RDF resource (RDF/XML, JSON-LD, Turtle)

Usage:

###
fetcher = new Fetcher()
fetcher.fetch 'http://www.w3.org/1999/02/22-rdf-syntax-ns#', null, (error, graph) ->
  console.log error if error
  console.log graph.toString() if graph
###

RDF resource Fetcher class:

rdf = require('rdf-interfaces');
require('rdf-ext')(rdf);
request = require('request')

class Fetcher

  self = null

  constructor: () ->
    self = this
    @parsers =
      'text/turtle': new rdf.TurtleParser()
      'application/json+ld': new rdf.JsonLdParser()
      'application/rdf+xml': new rdf.RdfXmlParser()

  accept_header: () ->
    accept = []
    accept.push parser for parser of @parsers
    
    "Accept": accept.join ', '

  content_type: (response) ->
    content_type = response.headers['content-type'].replace /;.*$/, ''

  fetch: (url, base, callback) ->
    options =
      url: url,
      headers: @accept_header()

    request options, (error, response, body) ->
      return callback(error) if error
      parser = self.parsers[self.content_type(response)]
      return callback(new Error '406') unless parser
      return parser.parse body,
        (graph) ->
          callback null, graph
        , base

module.exports = Fetcher
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment