Skip to content

Commit

Permalink
feat: add import function, closes #8
Browse files Browse the repository at this point in the history
  • Loading branch information
nokome committed Nov 25, 2018
1 parent bf3f905 commit 1cdf8b3
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 0 deletions.
54 changes: 54 additions & 0 deletions src/import.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import Thing from './Thing'
import * as types from './types'

/**
* Import a `Thing`.
*
* @param thing The thing to be imported
* @param format The current format of the thing as a MIME type e.g. `text/markdown`
* @returns An instance of a class derived from `Thing`
*/
export default function import_ (thing: string | object | Thing, format: string= 'application/ld+json'): Thing {
if (thing instanceof Thing) {
return thing
} else if (typeof thing === 'object') {
return importObject(thing)
} else {
switch (format) {
case 'application/ld+json':
return importJsonLd(thing)
default:
throw Error(`Unhandled import format: ${format}`)
}
}
}

/**
* Import an `Object` to a `Thing`
*
* This function demarshalls a plain JavaScript object into an
* instance of a class derived from `Thing` based on the `type`
* property of the object.
*
* @param object A plain JavaScript object with a `type` property
* @returns An instance of a class derived from `Thing`
*/
export function importObject (object: any): Thing {
const type = object.type
if (!type) throw new Error('Object is missing required "type" property')
// @ts-ignore
const Type = types[type]
if (!Type) throw new Error(`Unknown type "${type}"`)
return new Type(object)
}

/**
* Import a JSON-LD document to a `Thing`
*
* @param jsonld A JSON-LD document with a `type` property
* @returns An instance of a class derived from `Thing`
*/
export function importJsonLd (jsonld: string): Thing {
const object = JSON.parse(jsonld)
return importObject(object)
}
17 changes: 17 additions & 0 deletions tests/import.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import {default as import_, importJsonLd} from '../src/import'
import Thing from '../src/Thing'
import Person from '../src/Person'

test('import:Thing', () => {
const thing = new Thing()
expect(import_('{"type": "Thing"}')).toEqual(thing)
expect(import_({type: 'Thing'})).toEqual(thing)
expect(import_(thing)).toEqual(thing)

expect(import_('{"type": "Thing"}', 'application/ld+json')).toEqual(thing)
expect(() => import_("", 'foo/bar')).toThrow(/^Unhandled import format: foo\/bar/)
})

test('import:Person', () => {
expect(import_('{"type": "Person", "name": "Jane"}')).toEqual(new Person({name: "Jane"}))
})

0 comments on commit 1cdf8b3

Please sign in to comment.