diff --git a/src/convert.ts b/src/convert.ts new file mode 100644 index 0000000000..486d98ae27 --- /dev/null +++ b/src/convert.ts @@ -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) +} diff --git a/src/export.ts b/src/export.ts index 1b9b702b1c..b698b8b6d9 100644 --- a/src/export.ts +++ b/src/export.ts @@ -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) } diff --git a/tests/convert.test.ts b/tests/convert.test.ts new file mode 100644 index 0000000000..42ac3b3142 --- /dev/null +++ b/tests/convert.test.ts @@ -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/) +})