2016-09-16 19:22:12 +03:00
import Query from './query.js' ;
2017-06-28 10:34:42 +02:00
import NamedQuery from '../namedQuery/namedQuery.js' ;
2016-10-07 10:31:58 +03:00
import NamedQueryStore from '../namedQuery/store.js' ;
2016-09-16 19:22:12 +03:00
2017-06-28 10:34:42 +02:00
export default ( ... args ) => {
let name ;
let body ;
let rest ;
if ( typeof args [ 0 ] == 'string' ) { //NamedQuery
name = args [ 0 ] ;
body = args [ 1 ] ;
rest = args . slice ( 2 )
} else { //Query
body = args [ 0 ] ;
rest = args . slice ( 1 )
}
if ( _ . keys ( body ) . length > 1 ) {
2016-10-25 10:51:21 +03:00
throw new Meteor . Error ( 'invalid-query' , 'When using createQuery you should only have one main root point that represents the collection name.' )
2016-09-16 19:22:12 +03:00
}
2017-06-28 10:34:42 +02:00
const entryPointName = _ . first ( _ . keys ( body ) ) ;
2016-09-16 19:22:12 +03:00
2016-10-07 10:31:58 +03:00
const collection = Mongo . Collection . get ( entryPointName ) ;
2016-09-16 19:22:12 +03:00
if ( ! collection ) {
2017-06-28 13:42:50 +02:00
if ( name ) { //is a NamedQuery
2017-06-28 10:34:42 +02:00
throw new Meteor . Error ( 'invalid-name' , ` We could not find any collection with the name " ${ entryPointName } ". Make sure it is imported prior to using this ` )
}
2016-10-07 10:31:58 +03:00
const namedQuery = NamedQueryStore . get ( entryPointName ) ;
if ( ! namedQuery ) {
2016-10-25 10:51:21 +03:00
throw new Meteor . Error ( 'entry-point-not-found' , ` We could not find any collection or named query with the name " ${ entryPointName } ". Make sure you have them loaded in the environment you are executing *createQuery* ` )
2016-10-07 10:31:58 +03:00
} else {
2017-06-28 10:34:42 +02:00
return namedQuery . clone ( body [ entryPointName ] , ... rest ) ;
2016-10-07 10:31:58 +03:00
}
2016-09-16 19:22:12 +03:00
}
2017-06-28 10:34:42 +02:00
if ( name ) {
const query = new NamedQuery ( name , collection , body [ entryPointName ] , ... rest ) ;
NamedQueryStore . add ( name , query ) ;
2017-06-28 13:42:50 +02:00
2017-06-28 10:34:42 +02:00
return query ;
} else {
return new Query ( collection , body [ entryPointName ] , ... rest ) ;
}
2016-09-16 19:22:12 +03:00
}