Code Monkey home page Code Monkey logo

dinoql's Introduction

dinoql

Build Status license

A customizable GraphQL style query language for interacting with JavaScript objects. Use dinoql to traverse JavaScript objects the same way you query APIs with GraphQL.

Table of Contents

Installation

dinoql is available from npm.

$ npm install dinoql -S

Why ?

The main objective is to use the same idea of GraphQL, however instead of being for API, it will be for javascript objects.

Documentation

All examples are using this data:

const data = {
  requests: {
    products: [],
    
    users: [{
      name: 'Victor Igor',
      id: "100",
      age: 40
    }, {
      name: 'Kant Jonas',
      id: "200",
      age: 35
    }],
    
    friends: [{
      name: 'KΓ‘tia',
      id: "300",
      age: 10
    }]
  }
}

Getting only name from users

import dinoql from 'dinoql'

const users = dinoql(data)`
  requests {
    users {
      name
    }
  }
`

console.log(users) //{ users: [{ name: 'Victor Igor' }, { name: 'Kant Jonas' }] }

Get user by id

import dinoql from 'dinoql'

const users = dinoql(data)`
  requests {
    users(id: "200") {
      name
    }
  }
`

console.log(users) //{ users: [{ name: 'Kant Jonas' }] }

Aliases - Renaming keys

import dinoql from 'dinoql'

const users = dinoql(data)`
  requests {
    changeUsers: users(id: "200") {
      name
    }
  }
`

console.log(users) //{ changeUsers: [{ name: 'Kant Jonas' }] }

Variables

Build dynamic queries with variables.

const data = {
  users: [{
    name: 'Victor Igor',
    id: "100",
    age: 18
  }, {
    name: 'Paul Gilbert',
    id: "200",
    age: 35
  }],	
};

const variables = {
  id: "100"
};

const gql = dinoql(data, { variables })`
  users(id: $id) {
    name
  }
`

// { users: [{ name: 'Victor Igor' }] }

Conditions to get fields

You can create conditions to get a field.

const data = {
  dashboard: {
    value: '#54'	
  },
  
  name: 'Vic'
};

const variables = {
  cond: false
};

const gql = dql(data, { variables })` 
  dashboard(if: $cond) {
    value
  },
  name
}`;
//{ name: 'Vic' }

const otherGql = dql(data, { variables })` 
  dashboard(unless: $cond) {
    value
  },
  name
}`;
//{ name: 'Vic', value: '#54' }

Keep key from object

Sometimes, we need to keep specific keys.

const data = {
  requests: {
    user: {
      name: {
        text: 'Dinoql'
      },
      
      description: {
        text: 'I am dinoql.'
      }
    }
  }
}

If you wanna keep some keys, like:

//{ user: { name: 'Dinoql', description: 'I am dinoql.'} }

You can use (keep: true) in key, like:

import dinoql from 'dinoql'

//keeping user key
const user = dinoql(data)`
  requests {
    user(keep: true) {
       name {
         name: text
       },
       description {
         description: text
       }
    }
  }
`
//{ user: { name: 'Dinoql', description: 'I am dinoql.'} }

Resolvers

Resolvers provide the instructions for turning a dinoQL operation into data.

Order by

import dinoql from 'dinoql'

const users = dinoql(data)`
  requests {
    users(orderBy: age) {
      name,
      age
    }
  }
`

console.log(users) 

//{ users: [{ name: 'Kant Jonas', age: 35 }, { name: 'Victor Igor', age: 40 }] }

Merge

You can merge array or objects.

Array
import dinoql from 'dinoql'
const data = {
  requests: {
    users: [{ id: 10, age: 10 }]
  }
}

const variables = { 
  user: { id: 15, age: 40 }
}

const users = dinoql(data, { variables })`
  requests {
    users(merge: $user) {
      age
    }
  }
`

console.log(users) 

//{ users: [{ age: 10 }, { age: 40 }] }
Object
import dinoql from 'dinoql'
const data = {
  requests: {
    user: { id: 10, name: 'Victor Igor' }
  }
}

const variables = { 
  user: { age: 40 }
}

const user = dinoql(data, { variables })`
  requests {
    user(merge: $user)
  }
`

console.log(user) 

//{ user: { id: 10, name: 'Victor Igor', age: 40 } }

Default value

You can add default value to keys not found or values (null/undefined).

import dinoql from 'dinoql'

const users = dinoql(data)`
  requests {
    notfound(defaultValue: "Hello")
  }
`

console.log(users) 

// {notfound: "Hello"}

Parse to Number

import dinoql from 'dinoql'

const users = dinoql(data)`
  requests {
    users {
      id(toNumber: 1)
    }
  }
`

console.log(users)  //{ users: [{ id: 100 }, { id: 200 }] }

Get object values

import dinoql from 'dinoql'

const data = {
  requests: {
    user: {
      name: 'vic',
      age: 10
    }
  }
}
const gql = dinoql(data)`
  requests {
    user(getObjectValues: true)
  }
`

console.log(gql) //['vic', 10]

Parse to array

import dinoql from 'dinoql'

const data = {
  requests: {
    fields: {
      field1: 'name',
      field2: 'age'
    }
  }
}

const users = dinoql(data)`
  requests {
    fields(toArray: true)
  }
`

console.log(users)  //[{ field1: 'name' }, { field2: 'age' }]

First

import dinoql from 'dinoql'

const users = dinoql(data)`
  requests {
    users(first: true) {
      name
    }
  }
`

console.log(users)  //{ users: { name: 'Victor Igor' } }

Last

import dinoql from 'dinoql'

const users = dinoql(data)`
  requests {
    users(last: true) {
      name
    }
  }
`

console.log(users)  //{ users: { name: 'Kant Jonas' } }

Get Prop

import dinoql from 'dinoql'

const newData = {
  requests: {
    users: { id: 10, name: 'Victor Fellype' },
    information: { 
      title: { text: 'my title' }, 
      description: { text: 'my description' } 
    }
  }
};

without getProp

const data = dinoql(newData)`
  requests {
    users {
      name
    }
    information {
      title {
        title: text
      }
      description {
        description: text
      }
    }
  }
`

with getProp

const data = dinoql(newData)`
  requests {
    users(getProp: name)
    information {
      title(getProp: text)
      description(getProp: text)
    }
  }
`

console.log(data) // { users: 'Victor Fellype', title: 'my title', description: 'my description' }

Get Path

import dinoql from 'dinoql'

const newData = {
  requests: {
    cms: {
      footer_data: {
        social_networks: [
          { name: 'facebook', url: 'facebook.com' },
          { name: 'instagram', url: 'instagram.com' }
        ]
      }
    }
  }
};

without getPath

const data = dinoql(newData)`
  requests {
    cms {
      footer_data {
        social_networks
      }
    }
  }
`

with getPath

const socialNetworks = dinoql(newData)`
  requests(getPath: "cms.footer_data.social_networks")
`

console.log(socialNetworks) 
/* 
  { 
    requests: [ 
      { name: 'facebook', url: 'facebook.com' }, 
      { name: 'instagram', url: 'instagram.com' }
    ]
  }
*/

Building your own resolver

You can create a function to change a value in query.

import dql, { addResolvers } from 'dinoql';

const incAge = (list, right) => {
  const valueToInc = Number(right);
  return list.map(item => ({ ...item, age: item.age + valueToInc }));
};

addResolvers(({ incAge }));

const value = dql(data)`
  requests {
    users(incAge: 2) {
      name,
      age
    }
  }
`;
// { users: [{ name: 'Victor Igor', age: 42 }, { name: 'Kant Jonas', age: 37 }] }

Custom options

Keep structure

import dinoql from 'dinoql'

const users = dinoql(data, { keep: true })`
  requests {
    users(id: "200") {
      name
    }
  }
`

console.log(users)
/*
{ 
 requests: { 
   users: [{ name: 'Kant Jonas' }] 
 }
} 
*/

Improve performance πŸ„

You can improve performance parsing in build time your queries.

How ?

  1. Create files .graphql or .gql and add your queries.

  2. Import your queries from .graphql|.gql

# your queries

query MyQuery {
  requests {
    users
  }
}
//your js
import dinoql from 'dinoql'
import { MyQuery } from './MyQueries';

const users = dinoql(data)(MyQuery)
  1. Setup your webpack - example

Fragments support πŸ’₯

You can share piece of query logic.

fragment queryOne on Query {
  users {
    name
  }
}

fragment queryTwo on Query {
  products
}

query Form {
  requests {
    ...queryOne,
    ...queryTwo,
    friends
  }
}

Organizations and projects using dinoql

⚑️ List of organizations and projects using dinoql

License

The code is available under the MIT License.

dinoql's People

Contributors

rongfengliang avatar victorvoid avatar victufell avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

dinoql's Issues

Who uses dinoql?

If your company is using dinoql in production, please let us know who are you so we can mention you in the new README and forthcoming website.

Instructions:

  1. Share your company name.

  2. If your project is open source or public, please share a link!

  3. If you want it, you can share your logo (in which case it might be used in the readme/frontpage etc)

Get data from array instead of an object

I have an array of objects instead of an object with a property containing array.

I tried this query:

name
desc

and it returned this:

{ MyQuery: { [ name: ..., desc: ... ] ] } }

I don't need to have an object with "MyQuery" but want to get an array instead.

Here's where I use dinoql (in Next.js app):

import dql from 'dinoql'
import 'isomorphic-unfetch'

App.getInitialProps = async ({ query }) => {
  const res = await fetch(`http://localhost/api/reason`)
  const json = await res.json()

  return {
    query,
    reasons: dql(json)`
      name
      desc
    `.MyQuery
  }
}

Any ideas on how to avoid calling "MyQuery" property?

Support for GraphQL variables

Hi! Just a question. I have observed in your README as well as the source code and I'm still curious if there is any support for query variables in GraphQL. Great tool anyway, thanks!

Fragments support

The idea is to have fragments to use multiples queries.

like:

fragment queryOne on Query {
  users {
    name
  }
}

fragment queryTwo on Query {
  products
}

query Form {
  requests {
    ...queryOne,
    ...queryTwo,
    friends
  }
}

ReferenceError: window is not defined

when use with node env some error

ReferenceError: window is not defined 

this caused by webpack4

maybe change webpack.config.js with below

output: {
    path: path.resolve(__dirname, 'dist'),
    library: 'dinoql',
    libraryTarget: 'umd',
    filename: 'dinoql.min.js',
+   globalObject: 'typeof self !== \'undefined\' ? self : this',
  }

Apollo support

It would be awesome to use dinoql to polyfill graphql so react components using apollo can connect to a restful backend

TypeScript support

Hi, this project looks awesome!

I would really love to use this project with TypeScript. I see two main features:

  1. Typing existing functions (easy part)
  2. Make queries type sensetive
data: {
   users: {
      name: string
   }
}

const users = dinoql(data)`
    users {
      name
    }
`

And then we have users typed as { name: string }[]

Anyone tried dinoql in Deno?

dinoql seems very slick - I would like to use it in Deno and was curious if anyone's already tried it to see if it works outside of Node?

I checked on Pika as well but there wasn't an ES Module available.

Add custom resolvers via options

Sometimes we don't want to share resolvers across modules.

const gql = dinoql(data, {
  resolvers: { incAge: () => {} }
})

gql`{ requests { users(incAge: 1) { age } } }`

keep in keys is not working to multiple children

keep in keys is not working to multiple children

const newdata = {
  data: {
    users: {
      name: 'Victor Igor',
      id: "100",
      age: 40,
      test: {
        text: true,
        html: {
          _data: { text: 'hello', age: 10 }
        }
      }
    }
  }
};
const value = dql(newdata)`
  data {
    users(keep: true) {
      test {
        html(keep: true) {
          text: _data (getProp: text) 
          age: _data (getProp: age) 
        }
      }
    }
  }
  `;

received: { users: { html: { age: 10 } } }
expected: { users: { html: { text: 'hello', age: 10 } } }

undql - Removing keys by query

The idea is to remove the keys using query, like:

const data = { 
  users: [{ 
    name: 'Victor', age: 20, active: true 
  }]
}

const newuser = undql`
  users {
    age,
    active
  }
`

console.log(newuser) 
/*{ 
  users: [{ 
    name: 'Victor'
  }]
}*/

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.