1+ import { JsonSchemaParser } from "../src" ;
2+ import { readFile , mkdir , writeFile , stat } from 'fs/promises' ;
3+ import path from 'path' ;
4+
5+ describe ( 'JsonSchemaParser' , ( ) => {
6+
7+ beforeAll ( async ( ) => {
8+ await stat ( path . join ( __dirname , '.tmp' ) ) . catch ( async ( ) => {
9+ await mkdir ( path . join ( __dirname , '.tmp' ) ) ;
10+ } ) ;
11+ } ) ;
12+
13+ it ( 'should create instance' , ( ) => {
14+ const parser = new JsonSchemaParser ( ) ;
15+ expect ( parser ) . toBeTruthy ( ) ;
16+ } ) ;
17+ it ( 'should parse json schema' , async ( ) => {
18+ const parser = new JsonSchemaParser ( ) ;
19+ const schema = JSON . parse ( await readFile ( path . join ( __dirname , './schemas/UserProfile.json' ) , 'utf-8' ) ) ;
20+ const result = parser . parse ( schema , {
21+ name : 'UserProfile' ,
22+ title : 'User Profile' ,
23+ description : 'A user profile'
24+ } ) . get ( 'UserProfile' ) ;
25+ expect ( result ) . toBeTruthy ( ) ;
26+ await writeFile ( path . join ( __dirname , '.tmp/UserProfile.json' ) , JSON . stringify ( result , null , 2 ) ) ;
27+ expect ( result . name ) . toBe ( 'UserProfile' ) ;
28+ for ( const field of result . fields ) {
29+ expect ( field . name ) . toBeTruthy ( ) ;
30+ expect ( field . type ) . toBeTruthy ( ) ;
31+ }
32+ const email = result . fields . find ( field => field . name === 'email' ) ;
33+ expect ( email ) . toBeTruthy ( ) ;
34+ expect ( email . nullable ) . toBe ( false ) ;
35+ } ) ;
36+
37+ it ( 'should parse additional json schema' , async ( ) => {
38+
39+ const otherSchemas = [ ] ;
40+ const schema1 = JSON . parse ( await readFile ( path . join ( __dirname , './schemas/UserProfile.json' ) , 'utf-8' ) )
41+ schema1 . $name = 'UserProfile' ;
42+ otherSchemas . push ( schema1 ) ;
43+
44+ const parser = new JsonSchemaParser ( ) ;
45+ parser . resolvingSchema . subscribe ( ( event ) => {
46+ const schema = otherSchemas . find ( s => s . $id === event . id ) ;
47+ if ( schema ) {
48+ event . schema . push ( schema ) ;
49+ }
50+ } ) ;
51+
52+ const schema = JSON . parse ( await readFile ( path . join ( __dirname , './schemas/BlogPost.json' ) , 'utf-8' ) ) ;
53+ const results = parser . parse ( schema , {
54+ name : 'BlogPost' ,
55+ title : 'BlogPost' ,
56+ description : 'A blog post'
57+ } ) ;
58+ for ( const [ name , result ] of results ) {
59+ await writeFile ( path . join ( __dirname , `.tmp/${ name } .json` ) , JSON . stringify ( result , null , 2 ) ) ;
60+ expect ( result . name ) . toBe ( name ) ;
61+ for ( const field of result . fields ) {
62+ expect ( field . name ) . toBeTruthy ( ) ;
63+ expect ( field . type ) . toBeTruthy ( ) ;
64+ }
65+ }
66+ expect ( results . size ) . toBeGreaterThan ( 1 ) ;
67+ } ) ;
68+ } ) ;
0 commit comments