Skip to content

Commit

Permalink
feat: add convert function
Browse files Browse the repository at this point in the history
  • Loading branch information
nokome committed Nov 25, 2018
1 parent bb2e6b4 commit 359121b
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 2 deletions.
13 changes: 13 additions & 0 deletions src/convert.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import export_ from './export'
import import_ from './import'

/**
* Convert a thing from one format to another.
*
* @param thing The thing to convert as a string
* @param from The current format of the thing as a MIME type e.g. `text/markdown`
* @param to The desired format for the thing as a MIME type e.g. `text/html`
*/
export default function convert (thing: string, from: string= 'application/ld+json', to: string= 'application/ld+json'): string {
return export_(import_(thing, from), to)
}
5 changes: 3 additions & 2 deletions src/export.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,9 @@ export default function export_ (thing: Thing, format: string= 'application/ld+j
* @param thing The thing to be exported
*/
export function exportJsonLd (thing: Thing): string {
const obj = exportObject(thing)
obj['@context'] = 'https://stencila.github.io/schema/context.jsonld'
const obj = Object.assign({
'@context': 'https://stencila.github.io/schema/context.jsonld'
}, exportObject(thing))
return JSON.stringify(obj)
}

Expand Down
8 changes: 8 additions & 0 deletions tests/convert.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import convert from '../src/convert'

test('convert:Thing', () => {
const jsonld = '{"@context":"https://stencila.github.io/schema/context.jsonld","type":"Thing","name":"Thing1"}'
expect(convert(jsonld, 'application/ld+json', 'application/ld+json')).toEqual(jsonld)
expect(() => convert('blah', 'foo/bar')).toThrow(/^Unhandled import format: foo\/bar/)
expect(() => convert('{"type":"Person"}', undefined, 'foo/bar')).toThrow(/^Unhandled export format: foo\/bar/)
})

0 comments on commit 359121b

Please sign in to comment.