Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

graphql-model

Package Overview
Dependencies
Maintainers
1
Versions
8
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

graphql-model - npm Package Compare versions

Comparing version 0.0.4 to 0.0.6

248

lib/index.js

@@ -6,3 +6,2 @@ 'use strict';

});
exports.models = undefined;

@@ -13,4 +12,2 @@ var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
var _util = require('./util');

@@ -24,51 +21,53 @@

var defineStatic = function defineStatic(Class, name, value) {
Object.defineProperty(Class, name, {
value: value,
writable: false,
enumerable: false,
configurable: true
});
var createSetter = function createSetter(key) {
return function set(value) {
this._data[key] = value;
delete this._cache[key];
};
};
var defineGetterSetter = function defineGetterSetter(Class, name, get, set) {
Object.defineProperty(Class, name, {
get: get,
set: set,
enumerable: true,
configurable: true
});
var getGetter = function getGetter(obj, key) {
var _Object$getOwnPropert = Object.getOwnPropertyDescriptor(obj, key);
var get = _Object$getOwnPropert.get;
if (!get) {
throw new Error('Getter must be set for property, \'' + key + '\'');
}
return get;
};
var models = exports.models = {};
var models = {};
var createSetter = function createSetter(key) {
return function set(value) {
this._raw[key] = value;
delete this._cached[key];
};
var getModel = function getModel(model) {
return typeof model === 'string' ? models[model] : model;
};
var createGetter = function createGetter(key, Type) {
var createGetter = function createGetter(prototype, key, Type) {
if (Array.isArray(Type)) {
var _ret = function () {
// [Model]
if (key in prototype) {
var _ret2 = function () {
var getter = getGetter(prototype, key);
var FieldModel = Type[0];
return {
v: {
v: function get() {
var c = this._cache;
var _Type = _slicedToArray(Type, 1);
return c[key] || (c[key] = this.$createChildren(FieldModel, getter.call(this)));
}
}
};
}();
var FieldModel = _Type[0];
if ((typeof _ret2 === 'undefined' ? 'undefined' : _typeof(_ret2)) === "object") return _ret2.v;
}
var FieldModel = Type[0];
return {
v: function get() {
var _this = this;
var c = this._cache;
if (key in this._cached) {
return this._cached[key];
}
var list = this._raw[key];
var instances = list && list.map(function (item) {
return new FieldModel(item, _this);
});
this._cached[key] = instances;
return instances;
return c[key] || (c[key] = this.$createChildren(FieldModel, this._data[key]));
}

@@ -81,11 +80,22 @@ };

if (typeof Type === 'function') {
if (typeof Type === 'function' || typeof Type === 'string') {
// Model
if (key in prototype) {
var _ret3 = function () {
var getter = getGetter(prototype, key);
return {
v: function get() {
var c = this._cache;
return c[key] || (c[key] = this.$createChild(Type, getter.call(this)));
}
};
}();
if ((typeof _ret3 === 'undefined' ? 'undefined' : _typeof(_ret3)) === "object") return _ret3.v;
}
return function get() {
if (key in this._cached) {
return this._cached[key];
}
var instance = new Type(this._raw[key], this);
this._cached[key] = instance;
return instance;
var c = this._cache;
return c[key] || (c[key] = this.$createChild(Type, this._data[key]));
};

@@ -95,5 +105,5 @@ }

if (Type) {
// value
// Value
return function get() {
return this._raw[key];
return this._data[key];
};

@@ -110,3 +120,3 @@ }

var _ref$base = _ref.base;
var base = _ref$base === undefined ? Model : _ref$base;
var Base = _ref$base === undefined ? Model : _ref$base;
var _ref$interfaces = _ref.interfaces;

@@ -117,84 +127,75 @@ var interfaces = _ref$interfaces === undefined ? [] : _ref$interfaces;

var NewModel = function (_base) {
_inherits(NewModel, _base);
var NewModel = function (_Base) {
_inherits(NewModel, _Base);
function NewModel(data, parent) {
function NewModel() {
_classCallCheck(this, NewModel);
return _possibleConstructorReturn(this, Object.getPrototypeOf(NewModel).call(this, data, parent));
return _possibleConstructorReturn(this, Object.getPrototypeOf(NewModel).apply(this, arguments));
}
return NewModel;
}(base);
}(Base);
defineStatic(NewModel, 'name', Class.name);
defineStatic(NewModel, 'isModel', true);
defineStatic(NewModel, 'fields', fields);
defineStatic(NewModel, 'interfaces', interfaces);
var name = Class.name;
Object.keys(fields).forEach(function (key) {
return defineGetterSetter(NewModel.prototype, key, createGetter(key, fields[key]), createSetter(key));
if (models[name]) {
throw new Error('\'' + name + '\' model already exists!');
}
models[name] = NewModel;
(0, _util.defineClassName)(NewModel, name);
(0, _util.defineStatic)(NewModel, 'isModel', true);
(0, _util.defineStatic)(NewModel, 'fields', fields);
(0, _util.defineStatic)(NewModel, 'interfaces', interfaces);
[Class, Base].concat(interfaces).forEach(function (from) {
return (0, _util.inheritClass)(NewModel, from);
});
(0, _util.inheritClass)(NewModel, Class);
(0, _util.inheritClass)(NewModel, base);
interfaces.forEach(function (itfc) {
return (0, _util.inheritClass)(NewModel, itfc);
(0, _util.forEach)(fields, function (type, key) {
return (0, _util.defineGetterSetter)(NewModel.prototype, key, createGetter(NewModel.prototype, key, type), createSetter(key));
});
if (models[NewModel.name]) {
throw new Error('\'' + NewModel.name + '\' model already exists!');
}
models[NewModel.name] = NewModel;
return NewModel;
}
}, {
key: 'clear',
value: function clear() {
models = {};
}
}]);
function Model(data) {
var parent = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
function Model(data, parent, root) {
var context = arguments.length <= 3 || arguments[3] === undefined ? null : arguments[3];
_classCallCheck(this, Model);
this._raw = data;
this._parent = parent;
this._cached = {};
this._data = data;
this._parent = parent || null;
this._root = root || this;
this._context = context;
this._cache = {};
}
_createClass(Model, [{
key: 'destroy',
value: function destroy() {
delete this._raw;
key: '$destroy',
value: function $destroy() {
delete this._data;
delete this._parent;
delete this._cached;
delete this._context;
delete this._cache;
}
}, {
key: 'getRawData',
value: function getRawData() {
return this._raw;
key: '$field',
value: function $field(name) {
return this._data[name];
}
}, {
key: 'getRawValue',
value: function getRawValue(name) {
return this._raw[name];
}
}, {
key: 'getParent',
value: function getParent() {
return this._parent;
}
}, {
key: 'removeParent',
value: function removeParent() {
this._parent = null;
}
}, {
key: 'getParentOfType',
value: function getParentOfType(Type) {
if (!Type.isModel) {
Type = models[Type];
}
key: '$parentOfType',
value: function $parentOfType(type) {
var Model = getModel(type);
var p = this;
while (p = p._parent) {
if (p instanceof Type) {
if (p instanceof Model) {
return p;

@@ -206,15 +207,49 @@ }

}, {
key: 'clearCache',
value: function clearCache(key) {
key: '$createChild',
value: function $createChild(model, data) {
return new (getModel(model))(data, this, this._root, this._context);
}
}, {
key: '$createChildren',
value: function $createChildren(model, dataList) {
var _this2 = this;
return dataList && dataList.map(function (data) {
return _this2.$createChild(model, data);
});
}
}, {
key: '$clearCache',
value: function $clearCache(key) {
if (key) {
delete this._cached[key];
delete this._cache[key];
} else {
this._cached = {};
this._cache = {};
}
}
}, {
key: 'implements',
value: function _implements(Type) {
key: '$implements',
value: function $implements(Type) {
return this.constructor.interfaces.indexOf(Type) >= 0;
}
}, {
key: '$data',
get: function get() {
return this._data;
}
}, {
key: '$parent',
get: function get() {
return this._parent;
}
}, {
key: '$context',
get: function get() {
return this._context;
}
}, {
key: '$root',
get: function get() {
return this._root;
}
}]);

@@ -225,2 +260,3 @@

Model.get = getModel;
exports.default = Model;

@@ -6,2 +6,5 @@ 'use strict';

});
exports.forEach = forEach;
exports.defineStatic = defineStatic;
exports.defineGetterSetter = defineGetterSetter;
exports.inheritPropertyFrom = inheritPropertyFrom;

@@ -12,2 +15,56 @@ exports.inheritFrom = inheritFrom;

exports.inheritClass = inheritClass;
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function forEach(obj, fn) {
Object.keys(obj).forEach(function (key) {
return fn(obj[key], key, obj);
});
}
function defineStatic(Class, name, value) {
return Object.defineProperty(Class, name, {
value: value,
writable: false,
enumerable: false,
configurable: true
});
}
var defineClassName = void 0;
if (function () {
var A = function A() {
_classCallCheck(this, A);
};
try {
defineStatic(A, 'name', 'B');
return A.name === 'B';
} catch (e) {
return false;
}
}()) {
exports.defineClassName = defineClassName = function defineClassName(Class, value) {
return defineStatic(Class, 'name', value);
};
} else {
exports.defineClassName = defineClassName = function defineClassName(Class, value) {
// Old Node versions require the following options to overwrite class name.
return Object.defineProperty(Class, 'name', {
value: value,
writable: false,
enumerable: false,
configurable: false
});
};
}
exports.defineClassName = defineClassName;
function defineGetterSetter(Class, name, get, set) {
return Object.defineProperty(Class, name, {
get: get,
set: set,
enumerable: true,
configurable: true
});
};
function inheritPropertyFrom(objA, objB, key, asKey) {

@@ -14,0 +71,0 @@ return Object.defineProperty(objA, asKey || key, Object.getOwnPropertyDescriptor(objB, key));

{
"name": "graphql-model",
"version": "0.0.4",
"version": "0.0.6",
"description": "A data model class for wrapping a data object for easier resolving fields in GraphQL",

@@ -5,0 +5,0 @@ "main": "lib/index.js",

@@ -13,179 +13,284 @@ # graphql-model

```javascript
// Create a Node model
const Node = Model.create(class Node {
static isNode(obj) { return obj instanceof Node; }
get type() { return this.constructor.name; }
}, {
fields: {
id: true,
},
});
it('User', () => {
// Create a Node model
const Node = Model.create(class Node {
static isNode(obj) { return obj instanceof Node; }
get type() { return this.constructor.name; }
}, {
fields: {
id: true,
},
});
// Create a InfoInterface model
const InfoInterface = Model.create(class InfoInterface {}, {
fields: {
isPublic: true,
},
});
// Create a InfoInterface model
const InfoInterface = Model.create(class InfoInterface {}, {
fields: {
isPublic: true,
},
});
// Create a InfoBase model
const InfoBase = Model.create(class InfoBase {
static isInfo = (obj) => obj instanceof InfoBase
get user() { return this.getParentOfType('User'); }
isSharedWith(user) { return this.user.isFriendsWith(user); }
});
// Create a InfoBase model
const InfoBase = Model.create(class InfoBase {
static isInfo = (obj) => obj instanceof InfoBase
get user() { return this.$parentOfType('User'); }
isSharedWith(user) { return this.user.isFriendsWith(user); }
});
// Create a Name model
const NameModel = Model.create(class Name {
static isName(obj) { return obj instanceof NameModel; }
getFirstAndLastName() { return [this.firstName, this.lastName]; }
get shortName() { return `${this.firstName} ${this.lastName}`; }
get profile() { return this.getParent(); }
get profile2() { return this.getParentOfType(Profile); }
get profile3() { return this.getParentOfType('Profile'); }
}, {
base: InfoBase,
interfaces: [Node, InfoInterface],
fields: {
firstName: true,
lastName: true,
},
});
// Create a Name model
const NameModel = Model.create(class Name {
static isName(obj) { return obj instanceof NameModel; }
getFirstAndLastName() { return [this.firstName, this.lastName]; }
get shortName() { return `${this.firstName} ${this.lastName}`; }
get profile() { return this.$parent; }
get profile2() { return this.$parentOfType(Profile); }
get profile3() { return this.$parentOfType('Profile'); }
}, {
base: InfoBase,
interfaces: [Node, InfoInterface],
fields: {
firstName: true,
lastName: true,
},
});
// Create a Profile model
const Profile = Model.create(class Profile {}, {
fields: {
names: [NameModel],
},
});
// Create a Profile model
const Profile = Model.create(class Profile {}, {
fields: {
names: [NameModel],
},
});
// Create a User model
const User = Model.create(class User {
get friends() {
return Promise.resolve(this.getRawValue('friendIds').map((id) => ({id})));
}
isFriendsWith(user) {
return this.getRawValue('friendIds').indexOf(user.id) > -1;
}
}, {
interfaces: [Node],
fields: {
profile: Profile,
},
});
// Create a User model
const User = Model.create(class User {
get friends() {
return this.$field('friendIds').map((id) => ({id}));
}
isFriendsWith(user) {
return this.$field('friendIds').indexOf(user.id) > -1;
}
}, {
interfaces: [Node],
fields: {
profile: Profile,
hiddenField: false,
},
});
// Create a user instance
const user = new User({
id: '1',
profile: {
names: [{id: 'n1', firstName: 'F', lastName: 'L', isPublic: true}],
},
friendIds: ['2', '4'],
});
// Create a user instance
const user = new User({
id: '1',
profile: {
names: [{id: 'n1', firstName: 'F', lastName: 'L', isPublic: true}],
},
friendIds: ['2', '4'],
hiddenField: 1,
});
// static declared by interface Node
expect(user.id).to.equal('1');
// static declared by interface Node
expect(user.id).to.equal('1');
// dynamic field defined by interface Node
expect(user.type).to.equal('User');
// dynamic field defined by interface Node
expect(user.type).to.equal('User');
// undeclared field access
expect(user.friendIds).to.be.undefined;
// undeclared field access
expect(user.friendIds).to.be.undefined;
// access undeclared field
expect(user.getRawValue('friendIds')).to.eql(['2', '4']);
// access undeclared field
expect(user.$field('friendIds')).to.eql(['2', '4']);
// constructor
expect(user.constructor).to.equal(User);
// hidden field access
expect(user.hiddenField).to.be.undefined;
// instanceof
expect(user).to.be.an.instanceof(User);
// access hidden field
expect(user.$field('hiddenField')).to.equal(1);
// implements
expect(user.implements(Node)).to.be.true;
// set hidden field
user.hiddenField = 3;
expect(user.hiddenField).to.be.undefined;
expect(user.$field('hiddenField')).to.equal(3);
// dynamic field returns promise
expect(
user.friends.then(
(friends) => friends.map(({id}) => id)
)
).to.eventually.eql(user.getRawData().friendIds).notify(done);
// constructor
expect(user.constructor).to.equal(User);
// method
expect(user.isFriendsWith({id: '2'})).to.be.true;
expect(user.isFriendsWith({id: '1'})).to.be.false;
// instanceof
expect(user).to.be.an.instanceof(User);
// $implements
expect(user.$implements(Node)).to.be.true;
// instance field
const {profile} = user;
expect(profile).to.be.an.instanceof(Profile);
// dynamic field
expect(user.friends.map(({id}) => id)).to.eql(user.$data.friendIds);
// cached
expect(profile).to.equal(user.profile);
// method
expect(user.isFriendsWith({id: '2'})).to.be.true;
expect(user.isFriendsWith({id: '1'})).to.be.false;
// instance list field
const {names: [name]} = profile;
expect(name.constructor).to.equal(NameModel);
expect(name).to.be.an.instanceof(NameModel);
// instance field
const {profile} = user;
expect(profile).to.be.an.instanceof(Profile);
// cached
expect(name).to.equal(user.profile.names[0]);
// cached
expect(profile).to.equal(user.profile);
// base class
expect(name).to.be.an.instanceof(InfoBase);
// interfaces
expect(name.implements(Node)).to.be.true;
expect(name.implements(InfoInterface)).to.be.true;
// instance list field
const {names: [name]} = profile;
expect(name.constructor).to.equal(NameModel);
expect(name).to.be.an.instanceof(NameModel);
// field declared by Node
expect(name.id).to.equal('n1');
// cached
expect(name).to.equal(user.profile.names[0]);
// field declared by Node
expect(name.type).to.equal('Name');
// base class
expect(name).to.be.an.instanceof(InfoBase);
// declared field
expect(name.firstName).to.equal('F');
// interfaces
expect(name.$implements(Node)).to.be.true;
expect(name.$implements(InfoInterface)).to.be.true;
// declared field
expect(name.lastName).to.equal('L');
// field declared by Node
expect(name.id).to.equal('n1');
// method
expect(name.getFirstAndLastName()).to.eql(['F', 'L']);
// field declared by Node
expect(name.type).to.equal('Name');
expect(name.shortName).to.equal('F L');
// declared field
expect(name.firstName).to.equal('F');
// getParent
expect(name.profile).to.equal(profile);
// declared field
expect(name.lastName).to.equal('L');
// getParentOfType
expect(name.profile2).to.equal(profile);
expect(name.profile3).to.equal(profile);
// method
expect(name.getFirstAndLastName()).to.eql(['F', 'L']);
// getParentOfType declared by InfoBase
expect(name.user).to.equal(user);
expect(name.shortName).to.equal('F L');
// getParent
expect(name.getParent().getParent()).to.equal(user);
// $parent
expect(name.profile).to.equal(profile);
// inherited from base
expect(name.user).to.equal(user);
// $parentOfType
expect(name.profile2).to.equal(profile);
expect(name.profile3).to.equal(profile);
// inherited from base
expect(name.isSharedWith(user)).to.be.false;
expect(name.isSharedWith({id: '2'})).to.be.true;
expect(name.isSharedWith({id: '3'})).to.be.false;
// $parentOfType declared by InfoBase
expect(name.user).to.equal(user);
// inherited from InfoInterface
expect(name.isPublic).to.be.true;
// $parent
expect(name.$parent.$parent).to.equal(user);
// static method
expect(NameModel.isName(name)).to.be.true;
expect(NameModel.isName(user)).to.be.false;
expect(NameModel.isInfo(user)).to.be.false;
expect(NameModel.isInfo(name)).to.be.true;
expect(NameModel.isInfo).to.equal(InfoBase.isInfo);
// inherited from base
expect(name.user).to.equal(user);
// inherited from base
expect(name.isSharedWith(user)).to.be.false;
expect(name.isSharedWith({id: '2'})).to.be.true;
expect(name.isSharedWith({id: '3'})).to.be.false;
// inherited from InfoInterface
expect(name.isPublic).to.be.true;
// static method
expect(NameModel.isName(name)).to.be.true;
expect(NameModel.isName(user)).to.be.false;
expect(NameModel.isInfo(user)).to.be.false;
expect(NameModel.isInfo(name)).to.be.true;
expect(NameModel.isInfo).to.equal(InfoBase.isInfo);
// clear cache
expect(profile.names[0]).to.equal(name);
profile.$clearCache('names');
expect(profile.names[0]).to.not.equal(name);
expect(profile.names[0].id).to.equal(name.id);
// destory
user.$destroy();
expect(() => user.id).to.throw();
expect(user.$parent).to.be.undefined;
});
it('can pass down optional context', () => {
const GrandChild = Model.create(class GrandChild {}, {
fields: {
id: true,
},
});
const Child = Model.create(class Child {}, {
fields: {
id: true,
child: GrandChild,
},
});
const Parent = Model.create(class Parent {}, {
fields: {
child: Child,
},
});
const context = {};
const parent = new Parent({child: {child: {}}}, null, null, context);
expect(parent.$context).to.equal(context);
expect(parent.child.$context).to.equal(context);
expect(parent.child.child.$context).to.equal(context);
});
it('passes down a root instance', () => {
const GrandChild = Model.create(class GrandChild {}, {
fields: {
id: true,
},
});
const Child = Model.create(class Child {}, {
fields: {
id: true,
child: GrandChild,
},
});
const Parent = Model.create(class Parent {}, {
fields: {
child: Child,
},
});
const parent = new Parent({child: {child: {}}});
expect(parent.$root).to.equal(parent);
expect(parent.child.$root).to.equal(parent);
expect(parent.child.child.$root).to.equal(parent);
});
it('can create a child that is an instance of itself', () => {
const Selfie = Model.create(class Selfie {}, {
fields: {
child: 'Selfie',
},
});
const parent = new Selfie({child: {}});
expect(parent).to.be.an.instanceof(Selfie);
expect(parent.child).to.be.an.instanceof(Selfie);
});
it('can create a child of future model class', () => {
const Present = Model.create(class Present {}, {
fields: {
child: 'Future',
},
});
const Future = Model.create(class Future {});
const parent = new Present({child: {}});
expect(parent).to.be.an.instanceof(Present);
expect(parent.child).to.be.an.instanceof(Future);
});
```

@@ -192,0 +297,0 @@

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc