Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"presets": ["env"]
}
82 changes: 27 additions & 55 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,43 +1,15 @@
# graphql-query-builder
# mab-graphql-query-assembler

a simple but powerful graphQL query builder

**info:**

[![npm version](https://badge.fury.io/js/graphql-query-builder.svg)](https://badge.fury.io/js/graphql-query-builder)
[![License](http://img.shields.io/:license-mit-blue.svg)](http://doge.mit-license.org)
[![pull requests welcome](https://img.shields.io/badge/Pull%20requests-welcome-pink.svg)](https://github.com/codemeasandwich/graphql-query-builder/pulls)
[![GitHub stars](https://img.shields.io/github/stars/codemeasandwich/graphql-query-builder.svg?style=social&label=Star)](https://github.com/codemeasandwich/graphql-query-builder)


**tests:**

[![build](https://api.travis-ci.org/codemeasandwich/graphql-query-builder.svg)](https://travis-ci.org/codemeasandwich/graphql-query-builder)
[![Coverage Status](https://coveralls.io/repos/github/codemeasandwich/graphql-query-builder/badge.svg?branch=master)](https://coveralls.io/github/codemeasandwich/graphql-query-builder?branch=master)


**quality:**

[![Code Climate](https://codeclimate.com/github/codemeasandwich/graphql-query-builder/badges/gpa.svg)](https://codeclimate.com/github/codemeasandwich/graphql-query-builder)
[![bitHound Overall Score](https://www.bithound.io/github/codemeasandwich/graphql-query-builder/badges/score.svg)](https://www.bithound.io/github/codemeasandwich/graphql-query-builder)
[![Issue Count](https://codeclimate.com/github/codemeasandwich/graphql-query-builder/badges/issue_count.svg)](https://codeclimate.com/github/codemeasandwich/graphql-query-builder)
[![Known Vulnerabilities](https://snyk.io/test/npm/graphql-query-builder/badge.svg)](https://snyk.io/test/npm/graphql-query-builder)

### If this was helpful, [★ it on github](https://github.com/codemeasandwich/graphql-query-builder)

*tested on [**NodeJS**](https://nodejs.org) and [**Webpack**](https://webpack.github.io)*


## [Demo / Sandbox](https://tonicdev.com/codemeasandwich/57a0727c80254315001cb366) :thumbsup:

# Install

`npm install graphql-query-builder`
`npm install mab-graphql-query-assembler`

# Api

``` js
const Query = require('graphql-query-builder');
const Query = require('mab-graphql-query-assembler');
```

### constructor
Expand All @@ -46,11 +18,11 @@ query/mutator you wish to use, and an alias or filter arguments.
| Argument (**one** to **two**) | Description
|--- |---
| String | the name of the query function
| * String / Object | (**optional**) This can be an `alias` or `filter` values
| * String / Object | (**optional**) This can be an `alias` or `filter` values

``` js
let profilePicture = new Query("profilePicture",{size : 50});
```
```

### setAlias
set an alias for this result.
Expand All @@ -61,7 +33,7 @@ set an alias for this result.

``` js
profilePicture.setAlias("MyPic");
```
```

### filter
the parameters to run the query against.
Expand All @@ -72,7 +44,7 @@ the parameters to run the query against.

``` js
profilePicture.filter({ height : 200, width : 200});
```
```

### find
outlines the properties you wish to be returned from the query.
Expand All @@ -84,7 +56,7 @@ outlines the properties you wish to be returned from the query.

``` js
profilePicture.find( { link : "uri"}, "width", "height");
```
```

### toString
return to the formatted query string
Expand All @@ -96,7 +68,7 @@ return to the formatted query string
profilePicture+'';
// C
profilePicture.toString();
```
```

## run samples

Expand All @@ -106,31 +78,31 @@ node example/simple.js

# Example

``` js
var Query = require('graphql-query-builder');
``` js
var Query = require('mab-graphql-query-assembler');

// example of nesting Querys
let profilePicture = new Query("profilePicture",{size : 50});
profilePicture.find( "uri", "width", "height");

let user = new Query("user",{id : 123});
user.find(["id", {"nickname":"name"}, "isViewerFriend", {"image":profilePicture}])

console.log(user)
/*
user( id:123 ) {
id,
nickname : name,
isViewerFriend,

image : profilePicture( size:50 ) {
uri,
width,
height
}
}
*/

// And another example

let MessageRequest = { type:"chat", message:"yoyo",
Expand All @@ -146,13 +118,13 @@ let MessageRequest = { type:"chat", message:"yoyo",
{id:2,name:"tom"}
]
};

let MessageQuery = new Query("Message","myPost");
MessageQuery.filter(MessageRequest);
MessageQuery.find({ messageId : "id"}, {postedTime : "createTime" });

console.log(MessageQuery);

/*
myPost:Message( type:"chat",
message:"yoyo",
Expand All @@ -165,32 +137,32 @@ let MessageQuery = new Query("Message","myPost");
*/

// Simple nesting

let user = new Query("user");
user.find([{"profilePicture":["uri", "width", "height"]}])
/*

/*
user {
profilePicture {
uri,
width,
height
}
}
*/
*/

// Simple nesting with rename

let user = new Query("user");
user.find([{"image":{"profilePicture":["uri", "width", "height"]}}])
/*

/*
user {
image : profilePicture {
uri,
width,
height
}
}
*/
*/
```
34 changes: 34 additions & 0 deletions dist/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import 'babel-polyfill';
declare namespace GraphQLQueryBuilder {
interface FilterMap {
[key: string]: FilterMap | string | number;
}
namespace QueryDescriptor {
type Scalar = string;
interface Object {
[field: string]: QueryDescriptor;
}
interface Alias {
[alias: string]: QueryDescriptor;
}
type Field = Scalar | Object | Alias | GraphQLQueryBuilder;
}
type Field = QueryDescriptor.Field;
type QueryDescriptor = Field | Field[];
}
import FilterMap = GraphQLQueryBuilder.FilterMap;
import QueryDescriptor = GraphQLQueryBuilder.QueryDescriptor;
declare class GraphQLQueryBuilder {
operationName: string;
head: Array<FilterMap | string>;
alias?: string;
body?: string;
constructor(operationName: string);
constructor(operationName: string, filter?: FilterMap);
constructor(operationName: string, alias?: string);
find(find: QueryDescriptor): this;
setAlias(alias: string): this;
filter(filters: FilterMap): this;
toString(): string;
}
export default GraphQLQueryBuilder;
118 changes: 118 additions & 0 deletions dist/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
"use strict";

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

Object.defineProperty(exports, "__esModule", { value: true });
require("babel-polyfill");
//=====================================================
//========================================= Query Class
//=====================================================
var GraphQLQueryBuilder = /** @class */function () {
function GraphQLQueryBuilder(operationName, alias_OR_Filter) {
this.operationName = operationName;
this.head = [];
if ("string" === typeof alias_OR_Filter) {
this.alias = alias_OR_Filter;
} else if ("object" === (typeof alias_OR_Filter === "undefined" ? "undefined" : _typeof(alias_OR_Filter))) {
this.filter(alias_OR_Filter);
} else if (undefined === alias_OR_Filter && 2 === arguments.length) {
throw new TypeError("You have passed undefined as Second argument to 'Query'");
} else if (undefined !== alias_OR_Filter) {
throw new TypeError("Second argument to 'Query' should be an alias name(String) or filter arguments(Object). was passed " + alias_OR_Filter);
}
}
GraphQLQueryBuilder.prototype.find = function (find) {
if (!find) {
throw new TypeError("find value can not be >>falsy<<");
}
// if its a string.. it may have other values
// else it sould be an Object or Array of maped values
this.body = parceFind(Array.isArray(find) ? find : Array.from(arguments));
return this;
};
;
GraphQLQueryBuilder.prototype.setAlias = function (alias) {
this.alias = alias;
return this;
};
GraphQLQueryBuilder.prototype.filter = function (filters) {
var _this = this;
Object.entries(filters).filter(function (_a) {
var key = _a[0],
prop = _a[1];
return "function" !== typeof prop && "{}" !== getGraphQLValue(prop);
}).map(function (_a) {
var key = _a[0],
prop = _a[1];
return _this.head.push(key + ":" + getGraphQLValue(prop));
});
return this;
};
GraphQLQueryBuilder.prototype.toString = function () {
var queryArguments = 0 < this.head.length ? "(" + this.head.join(",") + ")" : "";
var alias = this.alias ? this.alias + ":" : "";
if (undefined === this.body) {
throw new ReferenceError("return properties are not defined. use the 'find' function to defined them");
}
return alias + " " + this.operationName + " " + queryArguments + " { " + this.body + " }";
};
return GraphQLQueryBuilder;
}();
//=====================================================
//============================ parce properties to find
//=====================================================
function parceFind(level) {
//+++++++++++++++++++++++++++++++++++ work over Array
//++++++++++++++++++++++++++++++++++++++++++++++++++++
return level.map(function (currentValue) {
if (currentValue instanceof GraphQLQueryBuilder) {
return currentValue.toString();
} else if (!Array.isArray(currentValue) && "object" === (typeof currentValue === "undefined" ? "undefined" : _typeof(currentValue))) {
return parseAlias(currentValue);
} else if ("string" === typeof currentValue) {
return currentValue;
} else {
throw new RangeError("cannot handle Find value of " + currentValue);
}
}).join(",");
}
function parseAlias(currentValue) {
var props = Object.keys(currentValue);
var prop = props[0];
var item = currentValue[prop];
if (1 !== props.length) {
throw new RangeError("Alias objects should only have one value. was passed: " + JSON.stringify(currentValue));
} else if (Array.isArray(item)) {
// contributor: https://github.com/charlierudolph/graphql-query-builder/commit/878328e857e92d140f5ba6f7cfe07837620ec490
return new GraphQLQueryBuilder(prop).find(item);
}
return prop + " : " + item + " ";
}
//=====================================================
//=================================== get GraphQL Value
//=====================================================
function getGraphQLValue(value) {
if ("string" === typeof value) {
return JSON.stringify(value);
} else if (Array.isArray(value)) {
return "[" + value.map(function (item) {
return getGraphQLValue(item);
}).join() + "]";
} else if ("object" === (typeof value === "undefined" ? "undefined" : _typeof(value))) {
return objectToString(value);
}
return value.toString();
}
function objectToString(obj) {
var source = Object.entries(obj).filter(function (_a) {
var key = _a[0],
prop = _a[1];
return "function" !== typeof prop;
}).map(function (_a) {
var key = _a[0],
prop = _a[1];
return key + ":" + getGraphQLValue(prop);
}).join();
return "{" + source + "}";
}
exports.default = GraphQLQueryBuilder;
Loading