Worked on the schema code

This commit is contained in:
2020-09-05 00:05:56 +10:00
parent e9655f1055
commit 7fa4c56bcc
6 changed files with 43 additions and 31 deletions

View File

@@ -1,6 +1,6 @@
{ {
"name": "simpleql", "name": "simpleql",
"version": "1.0.0", "version": "0.1.0",
"description": "", "description": "",
"main": "server/server.js", "main": "server/server.js",
"directories": { "directories": {

View File

@@ -21,7 +21,7 @@ let authors = [
}, },
]; ];
//insert the authors into the books //insert the authors into the books (relationship)
authors = authors.map(a => { authors = authors.map(a => {
a.books = a.books.map(b => { a.books = a.books.map(b => {
b.author = a; b.author = a;
@@ -39,4 +39,4 @@ authors.forEach(a => books = books.concat(a.books));
module.exports = { module.exports = {
authors, authors,
books, books,
}; };

View File

@@ -11,7 +11,7 @@ const database = require('./database.js');
//the handler routines //the handler routines
const handler = { const handler = {
Book: (parent, scalars) => { Book: (parent, scalars) => {
//takes an object which is the result of the parent query, if there is one { typeName: 'Author', scalars: [scalars], context: parentObject } //takes an object which is the result of the parent query, if there is one { typeName: 'Author', scalars: [scalars] }
//takes an array of scalar types as objects: { typeName: 'String', name: 'title' } //takes an array of scalar types as objects: { typeName: 'String', name: 'title' }
//must return an array of objects containing the results //must return an array of objects containing the results
@@ -82,4 +82,4 @@ const handler = {
}, },
}; };
module.exports = handler; module.exports = handler;

View File

@@ -2,13 +2,13 @@ module.exports = `
scalar Date scalar Date
type Book { type Book {
String title !String title
Author author Author author
Date published Date published
} }
type Author { type Author {
!String name !String name
!Book[] books Book[] books
} }
`; `;

View File

@@ -2,6 +2,7 @@
const express = require('express'); const express = require('express');
const bodyParser = require('body-parser'); const bodyParser = require('body-parser');
const app = express(); const app = express();
app.use(bodyParser.text()); app.use(bodyParser.text());
//test the library //test the library
@@ -20,4 +21,4 @@ app.post('/simpleql', async (req, res) => {
//startup //startup
app.listen(process.env.WEB_PORT || 3100, err => { app.listen(process.env.WEB_PORT || 3100, err => {
console.log(`listening to *:${process.env.WEB_PORT || 3100}`); console.log(`listening to *:${process.env.WEB_PORT || 3100}`);
}); });

View File

@@ -1,13 +1,24 @@
//reserved keywords that can't be used as identifiers
const keywords = ['type', 'scalar'];
//the main function to be returned //the main function to be returned
const main = (schema, handler) => { const main = (schema, handler) => {
const typeGraph = buildTypeGraph(schema); let typeGraph;
try {
typeGraph = buildTypeGraph(schema);
}
catch(e) {
console.log('caught in typegraph', e);
return null;
}
console.log(typeGraph); console.log(typeGraph);
//the receiving function - this will be called multiple times //the receiving function - this will be called multiple times
return async reqBody => { return async reqBody => {
//parse the query //parse the query
const tokens = reqBody.split(/(\s+)/).filter(s => s.trim().length > 0); const tokens = reqBody.split(/(\s+)/).filter(s => s.trim().length > 0); //TODO: proper token parsing
let pos = 0; let pos = 0;
try { try {
@@ -17,12 +28,12 @@ const main = (schema, handler) => {
case 'update': case 'update':
case 'delete': case 'delete':
throw 'keyword not implemented: ' + tokens[pos]; throw 'keyword not implemented: ' + tokens[pos];
//TODO //TODO: implement these keywords
break; break;
//no leading keyword - regular query //no leading keyword - regular query
default: default:
const result = await parseQuery(handler, tokens, pos, typeGraph[tokens[pos]], typeGraph); const result = await parseQuery(handler, tokens, pos, typeGraph);
return [200, result]; return [200, result];
@@ -47,7 +58,7 @@ const buildTypeGraph = schema => {
}; };
//parse the schema //parse the schema
const tokens = schema.split(/(\s+)/).filter(s => s.trim().length > 0); const tokens = schema.split(/(\s+)/).filter(s => s.trim().length > 0); //TODO: proper token parsing
let pos = 0; let pos = 0;
while (tokens[pos]) { while (tokens[pos]) {
@@ -57,12 +68,12 @@ const buildTypeGraph = schema => {
graph[tokens[pos]] = parseCompoundType(tokens, pos); graph[tokens[pos]] = parseCompoundType(tokens, pos);
//advance to the end of the compound type //advance to the end of the compound type
while(tokens[pos] && tokens[pos++] != '}'); pos = eatBlock(tokens, pos + 2); //+2: skip the name & opening bracket
break; break;
case 'scalar': case 'scalar':
if (['type', 'scalar'].includes(graph[tokens[pos]])) { if (keywords.includes(graph[tokens[pos]])) {
throw 'Unexpected keyword ' + graph[tokens[pos]]; throw 'Unexpected keyword ' + graph[tokens[pos]];
} }
@@ -95,11 +106,11 @@ const parseCompoundType = (tokens, pos) => {
//parse the extra typing data //parse the extra typing data
let array = false; let array = false;
let nullable = true; let required = false;
//not nullable //not nullable
if (type[0] === '!') { if (type[0] === '!') {
nullable = false; required = true;
type = type.slice(1); type = type.slice(1);
} }
@@ -114,32 +125,32 @@ const parseCompoundType = (tokens, pos) => {
checkAlphaNumeric(name); checkAlphaNumeric(name);
//can't use keywords //can't use keywords
if (['type', 'scalar'].includes(type) || ['type', 'scalar'].includes(name)) { if (keywords.includes(type) || keywords.includes(name)) {
throw 'Unexpected keyword found as type field or type name'; throw 'Unexpected keyword found as type field or type name (' + type + ' ' + name + ')';
} }
//check for duplicate fields //check for duplicate fields
if (Object.keys(compound).includes(name)) { if (Object.keys(compound).includes(name)) {
throw 'Unexpected duplicate filed name'; throw 'Unexpected duplicate field name';
} }
//finally, push to the compound definition //finally, push to the compound definition
compound[name] = { compound[name] = {
typeName: type, typeName: type,
array: array, array: array,
nullable: nullable, required: required,
}; };
} }
return compound; return compound;
}; };
const parseQuery = async (handler, tokens, pos, typeGraph, superTypeGraph, parent = null) => { const parseQuery = async (handler, tokens, pos, typeGraph, parent = null) => {
//returns an object result from handler //returns an object result from handler
//get the "parent object" contents for sub-objects //get the "parent object" contents for sub-objects
const queryName = superTypeGraph[tokens[pos]] ? null : tokens[pos]; //if you're a type, name = null // const queryName = typeGraph[tokens[pos]] ? null : tokens[pos]; //if you're a type, name = null
const queryType = superTypeGraph[tokens[pos]] ? tokens[pos] : superTypeGraph[parent.typeName][tokens[pos]].typeName; //use this type or derive the type from the parent // const queryType = typeGraph[tokens[pos]] ? tokens[pos] : typeGraph[parent.typeName][tokens[pos]].typeName; //use this type or derive the type from the parent
//move on //move on
pos++; pos++;
@@ -165,7 +176,7 @@ const parseQuery = async (handler, tokens, pos, typeGraph, superTypeGraph, paren
} }
//type is a scalar, and can be queried //type is a scalar, and can be queried
if (superTypeGraph[typeGraph[tokens[pos]].typeName].scalar) { if (typeGraph[typeGraph[tokens[pos]].typeName].scalar) {
//push the scalar object to the queryFields //push the scalar object to the queryFields
scalarFields.push({ typeName: typeGraph[tokens[pos]].typeName, name: tokens[pos] }); scalarFields.push({ typeName: typeGraph[tokens[pos]].typeName, name: tokens[pos] });
@@ -178,9 +189,8 @@ const parseQuery = async (handler, tokens, pos, typeGraph, superTypeGraph, paren
handler, handler,
tokens, tokens,
pos2, pos2,
superTypeGraph[typeGraph[tokens[pos2]].typeName], typeGraph,
superTypeGraph, { typeName: queryType, scalars: scalarFields } //parent object
{ typeName: queryType, scalars: scalarFields, context: result }
)]); )]);
pos = eatBlock(tokens, pos); pos = eatBlock(tokens, pos);
@@ -192,6 +202,7 @@ const parseQuery = async (handler, tokens, pos, typeGraph, superTypeGraph, paren
let results = handler[queryType](parent, scalarFields); let results = handler[queryType](parent, scalarFields);
//WTF
results = await Promise.all(results.map(async res => { results = await Promise.all(results.map(async res => {
const tuples = await Promise.all(deferredCalls.map(async call => await call(res))); const tuples = await Promise.all(deferredCalls.map(async call => await call(res)));
@@ -219,8 +230,8 @@ const eatBlock = (tokens, pos) => {
} }
} }
return pos; return ++pos;
}; };
//return //return
module.exports = main; module.exports = main;