Skip to content

Commit

Permalink
🚀 Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
flesch committed Feb 9, 2019
0 parents commit 8409157
Show file tree
Hide file tree
Showing 14 changed files with 4,342 additions and 0 deletions.
14 changes: 14 additions & 0 deletions .babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"presets": [
[
"@babel/preset-env",
{
"targets": {
"node": "6"
}
}
],
"@babel/preset-typescript"
],
"plugins": ["add-module-exports"]
}
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
dist
node_modules
*.log
npm-debug.log*
1 change: 1 addition & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
dist
9 changes: 9 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# .prettierrc
printWidth: 160
tabWidth: 2
useTabs: false
semi: true
singleQuote: true
trailingComma: "all"
bracketSpacing: true
arrowParens: "always"
76 changes: 76 additions & 0 deletions CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# Contributor Covenant Code of Conduct

## Our Pledge

In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.

## Our Standards

Examples of behavior that contributes to creating a positive environment
include:

* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members

Examples of unacceptable behavior by participants include:

* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting

## Our Responsibilities

Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.

Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.

## Scope

This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at . All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.

Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html

[homepage]: https://www.contributor-covenant.org

For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2019 John Flesch <john@fles.ch> (https://github.com/flesch)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
119 changes: 119 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
# graphql-flatten-path

The `info` argument of a GraphQL resolver [can often be mysterious](https://www.prisma.io/blog/graphql-server-basics-demystifying-the-info-argument-in-graphql-resolvers-6f26249f613a/), but it doesn't have to be! `graphql-flatten-path` will "flatten" that path taken through each resolver, resulting in a one dimensional array of `fieldNames`.

## Install

To get started, add `graphql-flatten-path` to your project:

<div>
<pre>$ npm install --save <a href="https://www.npmjs.com/package/graphql-flatten-path">graphql-flatten-path</a></pre>
</div>

## Usage

`graphql-flatten-path` is helpful when you're re-using resolvers or extending and stitching parts of a schema together, and need to know how the current field is nested under its ancestors.

It can be cumbersome to traverse a field's ancestors using `info.path`, which looks something like this:

```js
{
"prev": {
"prev": {
"prev": {
"key": "merchant"
},
"key": "transactions"
},
"key": 1
},
"key": "amount"
}
```

Instead, include `graphql-flatten-path` in your resolver to flatten `info.path` to an array of field names.

```diff
import { graphql } from 'graphql';
+ import flatten from 'graphql-flatten-path';

const resolvers = {
Query: {
merchant: async (parent, args, context, info) => {
+ const path = flatten(info.path, info.operation);
+ // path => ['query', 'merchant']
return context.db.getMerchants();
},
transactions: async (parent, args, context, info) => {
+ const path = flatten(info.path);
+ // path => ['transactions', index]
return context.db.transactions;
},
},
Transaction: {
amount: async (parent, args, context, info) => {
+ const path = flatten(info.path, info.operation);
+ // path => ['query', 'merchant', 'transactions', 1, 'amount']
+ // or ['query', 'transactions', index, 'amount']
return formatCurrency(parent.amount);
},
},
};
```

For a more advanced use case, take a look at the [included example project](https://github.com/flesch/graphql-flatten-path/blob/master/example) that uses `graphql-flatten-path` inside a "[middleware](https://github.com/prisma/graphql-middleware/)" function to log the execution time of each resolver (and show a warning if a resolver took too long).

```
WARNING: query.merchant ==> 980ms ∙ exceeds the threshold by 80ms!
INFO: query.merchant.id ==> 427ms
INFO: query.merchant.name ==> 682ms
INFO: query.merchant.transactions ==> 749ms
INFO: query.merchant.transactions.0.id ==> 412ms
INFO: query.merchant.transactions.1.amount ==> 438ms
INFO: query.merchant.transactions.1.id ==> 453ms
INFO: query.merchant.transactions.0.amount ==> 504ms
WARNING: query.merchant.transactions.1.date ==> 929ms ∙ exceeds the threshold by 29ms!
```

## Motivation

Not to say this module doesn't have merit, but it could have been as simple as something like this:

```js
import find from 'find-key';
export default function (path) => {
return find(path, 'key');
};
```

🙀 So why didn't I use an existing library like [find-key](https://github.com/simon-p-r/find-key)? Because I wanted to write something in Typescript and I like recursion, and I wanted to write something in Typescript and I like recursion.

## Contributing

[**graphql-flatten-path**](https://npm.im/graphql-flatten-path) is maintained by [John Flesch](mailto:john@fles.ch). Contributions are very much welcome!

## License

The MIT License (MIT)

Copyright (c) 2019 John Flesch <john@fles.ch> (https://github.com/flesch)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

<p align="center"><br /><sup>🐶 Made with <a href="https://www.instagram.com/murphythebeast/">a 7lb chiweenie</a> on my lap — near Chicago, IL</sup></p>
133 changes: 133 additions & 0 deletions example/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
// This example of graphql-flatten-path can be run directly with a later
// version of Node (supporting more modern JS features).
const { graphql } = require('graphql');
const { makeExecutableSchema } = require('graphql-tools');
const { applyMiddleware } = require('graphql-middleware');

// Make sure to run "npm link graphql-flatten-path" in this directory.
// graphql-flatten-path isn't saved in package.json.
const flatten = require('graphql-flatten-path');

// Sample data normally found in a database.
const db = {
transactions: [
{ id: 'AA4FBAgPDAIPDgEMBA8DBw', merchantId: 'CAYGCAYKAwYDBw8JBA8LDw', amount: 479.64, timestamp: 1549494790 },
{ id: 'BggDBwUICwYHAwwOBA0CDg', merchantId: 'Aw4ADQUMAQkPAwsMBAkKDg', amount: 613.57, timestamp: 1549411990 },
{ id: 'BQsKAQMICg0ABA0GBAYHCg', merchantId: 'CAYGCAYKAwYDBw8JBA8LDw', amount: 818.92, timestamp: 1548893590 },
{ id: 'DAwLCAwNDw8IDwQOBAEDBw', merchantId: 'AQwDDgAIBwABCAQBBA8IBQ', amount: 410.01, timestamp: 1546819990 },
{ id: 'BQcACAYFDA4ABgYMBAYHDw', merchantId: 'AgQJCAwOCQgADAMPBAENBw', amount: 272.13, timestamp: 1517962390 },
],
merchants: [
{ id: 'CAYGCAYKAwYDBw8JBA8LDw', name: 'Kozey - Gutmann, Inc' },
{ id: 'Aw4ADQUMAQkPAwsMBAkKDg', name: 'Hane Group, LLC' },
{ id: 'AQwDDgAIBwABCAQBBA8IBQ', name: 'Bogisich - Goldner' },
{ id: 'AgQJCAwOCQgADAMPBAENBw', name: 'Schamberger, Reinger and Schmidt' },
],
};

const typeDefs = `
type Merchant {
id: ID!
name: String!
transactions: [Transaction!]!
}
type Transaction {
id: ID!
merchant: Merchant!
amount: String!
date: String! # You want an official DateTime scalar too, right?
}
type Query {
merchant(id: ID!): Merchant!
transactions: [Transaction!]!
}
`;

// The usage section of the README said to add graphql-flatten-path to
// the resolvers, but they're missing here! Have we been lied to?!
const resolvers = {
Query: {
merchant: async (parent, args, context, info) => {
return context.db.merchants.find((merchant) => {
return merchant.id === args.id;
});
},
transactions: async (parent, args, context, info) => {
return context.db.transactions;
},
},
Merchant: {
transactions: async (parent, args, context, info) => {
return context.db.transactions.filter((transaction) => {
return transaction.merchantId === parent.id;
});
},
},
Transaction: {
merchant: async (parent, args, context, info) => {
return context.db.merchants.find((merchant) => {
return merchant.id === parent.merchantId;
});
},
amount: async (parent, args, context, info) => {
const amount = parseFloat(parent.amount).toFixed(2);
return `$${amount}`;
},
date: async (parent, args, context, info) => {
return new Date(parent.timestamp * 1000).toUTCString();
},
},
};

// There it is! We're using a "middleware" resolver to apply this logic
// to every resolver. I could never lie to you.
const logResponseTimeMiddleware = async (resolver, parent, args, context, info) => {
const path = flatten(info.path, info.operation).join('.');
const result = await resolver(parent, args, context, info);
const executionResponseTime = Date.now() - context.executionStartTime;
if (executionResponseTime > 900) {
console.warn(`WARNING: ${path} ==> ${executionResponseTime}ms ∙ exceeds the threshold by ${executionResponseTime - 900}ms!`);
} else {
console.log(`INFO: ${path} ==> ${executionResponseTime}ms`);
}
return result;
};

// For the purposes of this example, we're going to add some random
// latency to each resolver. Please don't actually do this.
// Note: This is defined after the "logResponseTimeMiddleware" middleware,
// but we'll apply it before further down.
const addLatencyMiddleware = async (resolver, parent, args, context, info) => {
const executionStartTime = Date.now();
await new Promise((resolve) => {
setTimeout(resolve, Math.floor(Math.random() * (1000 - 250 + 1)) + 250);
});
return resolver(parent, args, { ...context, executionStartTime }, info);
};

// You've seen the rest before, so run `node index.js` (or `node .` if that's
// your jam).

const query = `
query GetMerchantTransactions($merchantId: ID!) {
merchant(id: $merchantId) {
id
name
transactions {
id
amount
date
}
}
}
`;

const schema = makeExecutableSchema({ typeDefs, resolvers });
const schemaWithMiddleware = applyMiddleware(schema, addLatencyMiddleware, logResponseTimeMiddleware);

(async () => {
const result = await graphql(schemaWithMiddleware, query, {}, { db }, { merchantId: 'CAYGCAYKAwYDBw8JBA8LDw' });
console.log(JSON.stringify(result, null, 2));
})();
Loading

0 comments on commit 8409157

Please sign in to comment.