Skip to content

Commit

Permalink
feat: initialize the package
Browse files Browse the repository at this point in the history
  • Loading branch information
kyarik committed May 30, 2021
0 parents commit 040c0fa
Show file tree
Hide file tree
Showing 36 changed files with 11,382 additions and 0 deletions.
67 changes: 67 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
module.exports = {
env: {
browser: false,
node: true,
},
parser: '@typescript-eslint/parser',
plugins: ['@typescript-eslint'],
extends: [
'eslint:recommended',
'plugin:node/recommended',
'plugin:@typescript-eslint/all',
'prettier',
],
parserOptions: {
ecmaVersion: 2020,
project: './tsconfig.json',
sourceType: 'module',
},
rules: {
'@typescript-eslint/naming-convention': [
'error',
{
selector: 'default',
format: ['camelCase'],
leadingUnderscore: 'allow',
trailingUnderscore: 'allow',
},
{
selector: 'variable',
format: ['camelCase', 'UPPER_CASE'],
leadingUnderscore: 'allow',
trailingUnderscore: 'allow',
},
{
selector: 'typeLike',
format: ['PascalCase'],
},
{
selector: 'enumMember',
format: ['PascalCase'],
},
],
'@typescript-eslint/no-magic-numbers': [
'error',
{ ignoreArrayIndexes: true, ignoreEnums: true },
],
'@typescript-eslint/no-type-alias': [
'error',
{
allowAliases: 'always',
allowCallbacks: 'always',
allowLiterals: 'never',
allowMappedTypes: 'never',
},
],
'@typescript-eslint/prefer-readonly-parameter-types': 'off',
'node/no-missing-import': 'off',
'node/no-unsupported-features/es-syntax': 'off',
},
ignorePatterns: [
'/coverage',
'/dist',
'/integration-tests/**/*.js',
'/integration-tests/typescript/index.ts',
'/node_modules',
],
};
133 changes: 133 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
name: CI
on: [push, pull_request]
env:
NODE_VERSION: 14
jobs:
checks:
name: Checks
runs-on: ubuntu-latest
steps:
- name: Checkout repo
uses: actions/checkout@v2

- name: Setup NodeJS
uses: actions/setup-node@v1
with:
node-version: ${{ env.NODE_VERSION }}

- name: Cache NodeJS modules
uses: actions/cache@v2
with:
path: ~/.npm
key: ${{ runner.OS }}-node-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.OS }}-node-
- name: Install dependencies
run: npm ci

- name: Typecheck
run: npm run typecheck

- name: Lint
run: npm run lint

- name: Prettier check
run: npm run prettier:check

checkForCommonlyIgnoredFiles:
name: Check for commonly ignored files
runs-on: ubuntu-latest
steps:
- name: Checkout repo
uses: actions/checkout@v2

- name: Check if commit contains files that should be ignored
run: |
git clone --depth 1 https://github.com/github/gitignore.git &&
cat gitignore/Node.gitignore $(find gitignore/Global -name "*.gitignore" | grep -v ModelSim) > all.gitignore &&
if [[ "$(git ls-files -iX all.gitignore)" != "" ]]; then
echo "::error::Please remove these files:"
git ls-files -iX all.gitignore
exit 1
fi
integrationTests:
name: Integration tests
runs-on: ubuntu-latest
steps:
- name: Checkout repo
uses: actions/checkout@v2

- name: Setup NodeJS
uses: actions/setup-node@v1
with:
node-version: ${{ env.NODE_VERSION }}

- name: Install dependencies
run: npm ci

- name: Test
run: npm run test:integration

codeCoverage:
name: Code coverage
runs-on: ubuntu-latest
steps:
- name: Checkout repo
uses: actions/checkout@v2

- name: Setup NodeJS
uses: actions/setup-node@v1
with:
node-version: ${{ env.NODE_VERSION }}

- name: Cache NodeJS modules
uses: actions/cache@v2
with:
path: ~/.npm
key: ${{ runner.OS }}-node-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.OS }}-node-
- name: Install dependencies
run: npm ci

- name: Coverage
run: npm run test:coverage

- name: Upload to Codecov
if: ${{ always() }}
uses: codecov/codecov-action@v1
with:
file: ./coverage/coverage-final.json
fail_ci_if_error: true

test:
name: Tests on Node v${{ matrix.node_versions }}
runs-on: ubuntu-latest
strategy:
matrix:
node_versions: [10, 12, 14, 16]
steps:
- name: Checkout repo
uses: actions/checkout@v2

- name: Setup NodeJS v${{ matrix.node_versions }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node_versions }}

- name: Cache NodeJS modules
uses: actions/cache@v2
with:
path: ~/.npm
key: ${{ runner.OS }}-node-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.OS }}-node-
- name: Install dependencies
run: npm ci

- name: Test
run: npm run test
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/coverage
/dist
/node_modules
1 change: 1 addition & 0 deletions .husky/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
_
4 changes: 4 additions & 0 deletions .husky/commit-msg
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

npx --no-install commitlint --edit "$1"
3 changes: 3 additions & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/coverage
/dist
/node_modules
6 changes: 6 additions & 0 deletions .prettierrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"printWidth": 100,
"singleQuote": true,
"quoteProps": "consistent",
"trailingComma": "all"
}
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2021 Yaroslav Kukytsyak

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.
108 changes: 108 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
# A Middleware for Persisted Queries with express-graphql

`express-graphql-persisted-queries` is an HTTP server middleware for persisted queries designed to work with [`express-graphql`](https://github.com/graphql/express-graphql).

`express-graphql-persisted-queries` gives you a lot of flexibility by allowing you to specify a custom query ID key, a custom way to map a query ID to an actual query, and whether you want to allow only persisted queries for enhanced security.

`express-graphql-persisted-queries` also allows you to specify the persisted query ID both in the search params of a GET request and in the body of a POST request. This means that you can send HTTP GET requests for your GraphQL queries and laverage HTTP caching. This also means that you can preload queries with `<link rel="preload">`, starting to load data in parallel with code on the first page load.

Just like `express-graphql`, this middleware works with any HTTP web framework that supports connect styled middleware, including [Connect](https://github.com/senchalabs/connect), [Express](https://github.com/expressjs/express), and [Restify](https://github.com/restify/node-restify).

## Installation

Using yarn:

```
yarn add express-graphql-persisted-queries
```

Using npm:

```
npm install express-graphql-persisted-queries
```

## Usage

`express-graphql-persisted-queries` exports its middleware as the `persistedQueries` named export. So, you should import it as follows:

```ts
// Using ES modules
import { persistedQueries } from 'express-graphql-persisted-queries';

// Using CommonJS
const { persistedQueries } = require('express-graphql-persisted-queries');
```

Here's an example of the most basic usage, which assumes that we are sending the query ID under the `queryId` key in the search params or request body, and that we store the mapping from query ID to query in a JSON file.

```ts
import queryMap from './queryMap.json';

app.use('/graphql', persistedQueries({ queryMap }), graphqlHTTP({ schema }));
```

Notice that the `persistedQueries` middleware should be used before `graphqlHTTP`.

Here's a more advanced example in which we specify a custom query ID key, use the database to map the query ID to a query, and allow only persisted queries in production:

```ts
app.use(
'/graphql',
persistedQueries({
queryIdKey: 'id',
queryMap: (queryId) => getQueryTextFromDatabase(queryId),
strict: process.env.NODE_ENV === 'production',
}),
graphqlHTTP({ schema }),
);
```

## API

```ts
persistedQueries(options: Options): Middleware
```

### Parameters

- `options: Options` are the middleware options:

- `queryIdKey?: string` (default: `'queryId'`) is the key in the search params or request body that specifies the ID of the persisted query.
- `queryMap: QueryMap` is either an object mapping query IDs to query text or a function that receives the query ID as input and returns the query text, `null`, or a promise that resolves with query text or `null`. The `QueryMap` type is defined as follows:
```ts
type QueryMap = Record<string, Maybe<string>> | QueryMapFn;
type QueryMapFn = (queryId: string) => PromiseOrValue<Maybe<string>>;
```
- `strict?: boolean` (default: `false`) specifies whether only persisted queries are allowed. When `strict` is `true`, any request that contains the query text or that does not contain a valid query ID is considered invalid and results in a `400 Bad Request` error response.

### Return value

- `Middleware` an HTTP server middleware.

### Description

`persistedQueries` is used to create a middleware that adds support for persisted queries to your GraphQL HTTP server. This middleware should be specified before `graphqlHTTP` from `express-graphql`.

### Example

```ts
app.use(
'/graphql',
persistedQueries({
queryMap,
strict: process.env.NODE_ENV === 'production',
}),
graphqlHTTP({ schema }),
);
```

## Contributing

Pull requests are very welcome. If you intend to introduce a major change, please open a related issue first in which we can discuss what you would like to change.

Please make sure to update the tests and the README as appropriate.

## License

[MIT](https://github.com/kyarik/express-graphql-persisted-queries/blob/main/LICENSE)
27 changes: 27 additions & 0 deletions checkBranch.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Checks whether we are up to date with the main branch.

trap "exit 1" ERR

git fetch;

if [[ $? -ne 0 ]]; then
exit 1;
fi;

BRANCH=$(git branch -v | sed '/^[^*]/d');
BRANCH_NAME=$(echo "$BRANCH" | sed 's/* \([A-Za-z0-9_\-]*\).*/\1/');
BRANCH_SYNC=$(echo "$BRANCH" | sed 's/* [^[]*.\([^]]*\).*/\1/');

if [ "$BRANCH_NAME" != "main" ]; then
read -p "Current branch is not 'main' but '$BRANCH_NAME'. Continue? (y|N) " answer;
if [ "$answer" != "y" ] && [ "$answer" != 'Y' ]; then
exit 1;
fi;
fi;

if [ "$BRANCH_SYNC" != "" ]; then
read -p "Current branch is not up to date but '$BRANCH_SYNC'. Continue? (y|N) " answer;
if [ "$answer" != "y" ] && [ "$answer" != 'Y' ]; then
exit 1;
fi;
fi;
14 changes: 14 additions & 0 deletions codecov.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
codecov:
notify:
require_ci_to_pass: yes

parsers:
javascript:
enable_partials: yes

comment: no
coverage:
status:
project:
default:
target: auto

0 comments on commit 040c0fa

Please sign in to comment.