Skip to content

Commit

Permalink
Merge pull request #8 from thuoe/next
Browse files Browse the repository at this point in the history
Release `next`: 2024/03/01
  • Loading branch information
thuoe authored Mar 1, 2024
2 parents 5fd6ec6 + 7ed913d commit 765ad20
Show file tree
Hide file tree
Showing 27 changed files with 22,506 additions and 0 deletions.
7 changes: 7 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
^root = true

[*]
charset = utf-8
insert_final_newline = true
indent_style = space
indent_size = 2
15 changes: 15 additions & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/* eslint-env node */
{
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"prettier"
],
"parser": "@typescript-eslint/parser",
"plugins": ["@typescript-eslint"],
"root": true,
"rules": {
"quotes": ["error", "single"]
},
"ignorePatterns": ["dist/**", "*.config.js"]
}
26 changes: 26 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
name: CI Pipeline
on:
push:
branches:
- next
pull_request:
branches:
- next
jobs:
SimpleCI:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Check out repository code & install node
uses: actions/setup-node@v2
with:
node-version: "18"
cache: "npm"
- name: Install
run: "npm ci"
- name: Build
run: "npm run build:prod"
- name: Lint
run: npm run lint
- name: Unit Test
run: npm run test
33 changes: 33 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
name: Release
on:
push:
branches:
- main

permissions:
contents: read

jobs:
release:
name: Release
runs-on: ubuntu-latest
permissions:
contents: write
issues: write
pull-requests: write
steps:
- name: Checkout
uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: "lts/*"
- name: Install
run: npm ci
- name: Release
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
run: npm run release
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
node_modules
dist
bundle
13 changes: 13 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
.github
.vscode
bundle
server
src
test
.editorconfig
.eslintrc.json
.prettierrc
jest.config.js
nodemon.json
tsconfig.json
tsconfig.*.json
1 change: 1 addition & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{}
7 changes: 7 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "explicit"
},
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
}
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) 2024 Eddie Thuo

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.
197 changes: 197 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,197 @@
<h1 align="center">gql-util-directives</h1>

<p align="center">
<a href="https://github.com/thuoe/gql-util-directives/actions/workflows/ci.yml">
<img src="https://github.com/thuoe/gql-util-directives/actions/workflows/ci.yml/badge.svg?branch=next" alt="CI status">
</a>
</p>

<h3 align="center">
Simple utility library for custom GraphQL schema directives
</h3>

- [Get started](#get-started)
- [Local Development](#local-development)
- [Directives](#directives)
- [@encode `encodingDirective()`](#encode-encodingdirective)
- [@regex `regexDirective()`](#regex-regexdirective)
- [@cache `cacheDirective()`](#cache-cachedirective)
- [Overriding in-memory cache](#overriding-in-memory-cache)

# Get started

Install package:

```sh
npm install --save @thuoe/gql-util-directive
```

Example of importing the `@regex` directive & instantiating with Apollo Server:

```typescript
import { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';
import { makeExecutableSchema } from '@graphql-tools/schema';
import directives from "@thuoe/gql-util-directives";

const typeDefs = String.raw`#graphql
type User {
firstName: String
lastName: String @regex(pattern: "\\b[A-Z]\\w+\\b")
age: Int
}
type Query {
user: User
}
`;

const resolvers = {
Query: {
user: () => ({
firstName: 'Michael',
lastName: 'Jordan',
age: 61,
})
},
};

const { regexDirective } = directives
const { regexDirectiveTypeDefs, regexDirectiveTransformer } = regexDirective('regex')

const transformers = [
regexDirectiveTransformer,
]

let schema = makeExecutableSchema(({
typeDefs: [
regexDirectiveTypeDefs,
typeDefs
],
resolvers
}))

schema = transformers.reduce((curSchema, transformer) => transformer(curSchema), schema)

const server = new ApolloServer({
schema,
});

startStandaloneServer(server, {
listen: { port: 4000 },
}).then(({ url }) => {
console.log(`🚀 Server ready at: ${url}`);
})
```

Here are the possible directive functions that are exposed as part of this util package:

`regexDirective | encodingDirective | cacheDirective`

# Local Development

Install local dependencies:

```sh
npm install
```

Run local environment (Apollo Studio):

```sh
npm run dev
```

Link to Apollo Studio can be found on http://localhost:4000 to perform mutations and queries.

# Directives

## @encode `encodingDirective()`

You can use the `@encode` directive on fields defined using the `String` scalar type.

Following encoding methods:

`ascii | utf8 | utf16le | ucs2 | base64 | base64url | latin1 | binary | hex`

```graphql
type User {
firstName: String @encode(method: "hex")
lastName: String @encode(method: "base64")
}
```

## @regex `regexDirective()`

You can use the `@regex` directive to validate fields using the `String` scalar type. It will throw an
`ValidationError` in the event that the pattern defined has a syntax if no matches are found against the field value.

```graphql
type User {
firstName: String @regex(pattern: "(John|Micheal)")
lastName: String @regex(pattern: "\\b[A-Z]\\w+\\b")
}
```

⚠️ Escaping characters

If you are defining a regex pattern using backslashes must escape them (`//`) **and** pattern invoke the function `String.raw()` to the schema so that the escape characters are not ignored:

```typescript
const typeDefs = String.raw`
type User {
firstName: String @regex(pattern: "(Eddie|Sam)")
lastName: String @regex(pattern: "\\b[A-Z]\\w+\\b")
age: Int
}

type Query {
user: User
}
`;
```

## @cache `cacheDirective()`

You can use `@cache` directive to take advantage of a in-memory cache for a field value

```graphql
type Book {
name: String
price: String @cache(key: "book_price", ttl: 3000)
}
```

`key` - represents the unique key for field value you wish to cache

`ttl` - time-to-live argument for how long the field value should exist within the cache before expiring (in milliseconds)

### Overriding in-memory cache

If you wish to take leverage something more powerful (for example [Redis](https://redis.io/)), you can override the in-memory solution with your own implementation.

Example:

```typescript
import Redis from 'ioredis'

const redis = new Redis()
....
const cache = {
has: (key: string) => redis.exists(key),
get: (key: string) => redis.get(key),
delete:(key: string) => redis.delete(key),
set: async (key: string, value: string) => {
await redis.set(key, value)
},
}
...
const { cacheDirectiveTypeDefs, cacheDirectiveTransformer } = cacheDirective('cache', cache)
```

You must confirm to this set of function signatures to make this work:

- `has: (key: string) => Promise<boolean>` Checks if a key exists in the cache.
- `get: (key: string) => Promise<string>` Retrieves the value associated with a key from the cache.
- `set: (key: string, value: string) => Promise<void>` Sets a key-value pair in the cache.
- `delete: (key: string) => Promise<boolean>` Deletes a key and its associated value from the cache.
9 changes: 9 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
preset: "ts-jest",
testEnvironment: "node",
moduleNameMapper: {
"^@src/(.*)$": "<rootDir>/src/$1",
"^@src/directives/(.*)$": "<rootDir>/src/directives/$1",
},
};
5 changes: 5 additions & 0 deletions nodemon.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"watch": ["src", "server"],
"ext": "ts",
"exec": "ts-node -r tsconfig-paths/register"
}
Loading

0 comments on commit 765ad20

Please sign in to comment.