Compare commits

...

5 Commits

@ -9,3 +9,65 @@ dlayer differs from GraphQL in a number of important ways:
- dlayer supports recursive queries without needing schema hacks; both bounded and unbounded.
- dlayer is modular by default; a dlayer API can be composed of many independent 'modules' that can reference and extend each other when available. This allows for eg. constructing plugin systems, like in [sysquery](FIXME), as well as making it easier to loosely couple your API definition.
- dlayer does not use a separate schema; the schema is implicitly defined by what the API returns. This essentially makes it dynamically typed; however, trying to access a non-existent property of the schema is an error.
## Module format
A module is an object of the following shape:
```js
{
name: "a unique name/identifier for the module",
makeContext: function() {
// A function that returns a fresh set of context values (called once per query)
return {
// This can contain simple values, but also initialized functions,
// database instances, whatever stateful thing your type implementations need.
// Whatever you specify here will *only* be available in the context from
// within the methods that are defined in this module, not in other modules!
};
},
types: {
"your-app.type-name": function(args) {
// NOTE: No context is available here; this function is just meant to construct
// a new object 'shape', not to do any business logic
return {
someStaticProperty: "foo",
someDynamicProperty: async function(propertyArgs, context) {
// Do some dynamic logic here, potentially using stuff from the context
return whatever;
}
};
}
},
extensions: {
"your-app.type-from-another-module": {
extendedProperty: async function(propertyArgs, context) {
// Some dynamic logic, same as a normal type function, except this module
// doesn't need to "own" that type to attach its own properties to it.
return whatever;
}
}
},
root: {
some: {
nested: {
path: async function(args) {
// Again, some dynamic logic, maybe we want to create some instance of
// our custom type here?
return $make("your-app.type-name", {});
}
}
}
}
}
```
## Properties of the context
- `async $getProperty(object, propertyName)`: internally resolve and return the specified property on the specified object (use `this` as a reference to the object that the method is defined on)
- `async $getPropertyPath(object, propertyPath)`: like `$getProperty`, but accepts a property path (period-delimited string or array of path component strings)
- `async $make(typeName, arguments)`: creates a new instance of the specified type
- `async $maybeMake(typeName, arguments)`: like `$make`, but silently returns undefined if the type doesn't exist; typically used for optional schema add-ons
- `$getModuleContext(moduleName)`: __you should not need this in normal usage!__ This is an escape hatch to access the context of a module by that module's `name`; it's typically only necessary when eg. developing utilities for dlayer that provide queries separately for the user to place somewhere in their schema, as those queries will technically execute outside of any module
Aside from these utility functions, the context will also contain all the properties that were returned from your `makeContext` methods.

@ -18,6 +18,7 @@ const InvalidObject = require("./invalid-object");
// FIXME: recurseDepth, recurseLabel/recurseGoto
// TODO: Internal queries, but only in modules, and only as a last resort
// TODO: Throw a useful error when trying to $make a non-existent type
// TODO: Refactor using stand-alone utility functions
/* Process design:
@ -73,22 +74,6 @@ function isObject(value) {
return (value != null && typeof value === "object" && !Array.isArray(value));
}
// TODO: Move to separate package, decide whether to keep the nested array detection or not - that should probably just be part of the handler?
function mapMaybeArray(value, handler) {
// NOTE: This is async!
if (Array.isArray(value)) {
return Promise.map(value, (item, i) => {
if (Array.isArray(item)) {
throw new Error(`Encountered a nested array, which is not allowed; maybe you forgot to flatten it?`);
} else {
return handler(item, i);
}
});
} else {
return handler(value);
}
}
/* Possible values of a schema property:
true, null, object with only special keys (but not $recurse) -- fetch value and return it as-is
false -- do not fetch value at all
@ -251,6 +236,7 @@ module.exports = function createDLayer(options) {
let combinedContext = {
... generatedContext,
... context,
$getModuleContext: getModuleContext,
// FIXME: Figure out a way to annotate errors here with the path at which they occurred, *and* make clear that it was an internal property lookup
$getProperty: getProperty,
$getPropertyPath: function (object, propertyPath) {
@ -277,6 +263,17 @@ module.exports = function createDLayer(options) {
let getContextForModule = loaded.makeContextFactory(combinedContext);
function getModuleContext(moduleName) {
// NOTE: This is an escape hatch to access a module's context from outside of that module; you should not normally need this!
if (loaded.nameToID.has(moduleName)) {
let moduleID = loaded.nameToID.get(moduleName);
console.log({moduleName, moduleID});
return getContextForModule(moduleID);
} else {
throw new Error(`No module named '${moduleName}' has been loaded`);
}
}
function getProperty(object, property, args = {}) {
// TODO: Should this allow a single-argument, property-string-only variant for looking up properties on self?
// FIXME: Validatem
@ -293,7 +290,7 @@ module.exports = function createDLayer(options) {
}
async function make(typeID, args, existenceRequired) {
let type = loaded.types[typeID].func;
let type = loaded.types[typeID];
if (type == null) {
if (existenceRequired === true) {
@ -302,7 +299,7 @@ module.exports = function createDLayer(options) {
return;
}
} else {
let instance = await type(args);
let instance = await type.func(args, getContextForModule(type.__moduleID));
if (loaded.extensions[typeID] != null && instance !== InvalidObject) {
for (let [ key, extension ] of Object.entries(loaded.extensions[typeID])) {

@ -32,12 +32,12 @@ function createTypeTracker() {
throw new Error(`Type '${name}' already exists (from module '${module.name}', already defined by module '${existingEntry.source.name}')`);
} else {
typeFactories[name] = {
__moduleID: getModuleID(module),
source: module,
// No context provided to type factory functions for now, since they are not allowed to be async for now anyway
// FIXME: Maybe add a warning if the user returns a Promise from a factory, asking them to file a bug if they really need it?
// func: wrapModuleFunction(module, factory)
func: async function (... args) {
let instance = await factory(... args);
func: async function (args, context) {
// NOTE: We pass through the context here without modifying it; because a module-specific context will be injected from the main runtime
let instance = await factory(args, context);
if (instance !== InvalidObject) {
// We need to patch every created object, so that the correct context gets injected into its type-specific methods when they are called
@ -104,9 +104,11 @@ function defaultContext() {
module.exports = function (modules) {
// TODO: Eventually replace hand-crafted merging logic with merge-by-template, once it can support this usecase properly(tm)
// TODO: Fix merge-by-template so that reasonable error messages can be generated here, that are actually aware of eg. the conflicting key
// TODO: Disallow modules with duplicate names? This may be necessary to prevent issues with getModuleContext, which provides name-based context access
let types = createTypeTracker();
let typeExtensions = createExtensionTracker();
let nameToID = new Map(); // TODO: Make this a tracker abstraction?
let contextFactories = syncpipe(modules, [
_ => _.map((module) => [ getModuleID(module), module.makeContext ?? defaultContext ]),
@ -118,6 +120,10 @@ module.exports = function (modules) {
}, {});
for (let module of modules) {
if (module.name != null) {
nameToID.set(module.name, getModuleID(module));
}
for (let [ type, factory ] of Object.entries(module.types ?? {})) {
types.add(module, type, factory);
}
@ -133,6 +139,7 @@ module.exports = function (modules) {
root: schema,
types: types.get(),
extensions: typeExtensions.get(),
nameToID: nameToID,
makeContextFactory: function (baseContext) {
let cache = new Map();

@ -1,6 +1,6 @@
{
"name": "dlayer",
"version": "0.2.0",
"version": "0.2.1",
"main": "index.js",
"repository": "https://git.cryto.net/joepie91/dlayer.git",
"author": "Sven Slootweg <admin@cryto.net>",

Loading…
Cancel
Save