Skip to content

Commit

Permalink
feat(graphql): initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
sastan committed Jul 13, 2020
1 parent 88d96a0 commit 2016bee
Show file tree
Hide file tree
Showing 25 changed files with 2,094 additions and 0 deletions.
21 changes: 21 additions & 0 deletions packages/graphql/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2020 [these people](https://github.com/kenoxa/svelkit/graphs/contributors)

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.
93 changes: 93 additions & 0 deletions packages/graphql/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
# @svelkit/graphql

> A lightweight [GraphQL] client for [svelte]
[![License](https://badgen.net/npm/license/@sveltik/graphql)](https://github.com/kenoxa/@sveltik/graphql/blob/main/LICENSE)
[![Latest Release](https://badgen.net/npm/v/@sveltik/graphql)](https://www.npmjs.com/package/@sveltik/graphql)
[![View changelog](https://badgen.net/badge/%E2%80%8B/Explore%20Changelog/green?icon=awesome)](https://changelogs.xyz/@sveltik/graphql)
[![Bundle Size](https://badgen.net/bundlephobia/minzip/@sveltik/graphql)](https://bundlephobia.com/result?p=@sveltik/graphql)

## What?

Use [GraphQL] APIs in [svelte] the svelte way. Either as [readable store](https://svelte.dev/docs#svelte_store) or using [promises](https://svelte.dev/docs#await).

## Why?

Existing solutions ([graphql-svelte](https://www.npmjs.com/package/graphql-svelte), [@urql/svelte](https://github.com/FormidableLabs/urql/tree/main/packages/svelte-urql), and [others](https://www.npmjs.com/search?q=svelte%20graphql)) didn't provide the API we were looking for, features we would not need or were to heavy.

This solutions focuses on a _native_ svelte API using [svelte/store](https://svelte.dev/docs#svelte_store).

<!-- prettier-ignore-start -->
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->


- [@svelkit/graphql](#svelkitgraphql)
- [What?](#what)
- [Why?](#why)
- [Installation](#installation)
- [Usage](#usage)
- [License](#license)

<!-- END doctoc generated TOC please keep comment here to allow auto update -->
<!-- prettier-ignore-end -->

## Installation

```sh
npm install @sveltik/graphql
```

And then import it:

```js
// using es modules
import { useQuery, gql } from '@sveltik/graphql'

// common.js
const { useQuery, gql } = require('@sveltik/graphql')
```

Alternatively use [UNPKG](https://unpkg.com/@sveltik/graphql/) or [jsDelivr](https://cdn.jsdelivr.net/npm/@sveltik/graphql/) packages.

Hotlinking from unpkg: _(no build tool needed!)_

```js
import { useQuery, gql } from 'https://unpkg.com/@sveltik/graphql?module'
```

## Usage

```html
<script>
import { initGraphQLClient, useQuery, gql } from '@sveltik/graphql'
initGraphQLClient({ url: 'https://swapi.graph.cool/' })
const films = useQuery(gql`
query {
allFilms {
id
title
releaseDate
}
}
`)
</script>

{#if $films.fetching} Loading ... {:else if $films.error} Ups... {$films.error.message} {:else}
<ol>
{#each $films.data.allFilms as film (film.id)}
<li>{film.title} - {file.releaseDate}</li>
{/each}
</ol>
{/if}
```

## License

`sveltik` is open source software [licensed as MIT](https://github.com/kenoxa/sveltik/blob/main/LICENSE).

[sveltik]: https://sveltik.js.org/
[svelte]: https://svelte.dev/
[graphql]: https://graphql.org/
1 change: 1 addition & 0 deletions packages/graphql/package-scripts.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = require('@carv/snowpack-scripts/nps-preset')
52 changes: 52 additions & 0 deletions packages/graphql/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
{
"name": "@svelkit/graphql",
"version": "0.0.0-dev",
"private": true,
"keywords": [
"sveltik",
"svelte",
"graphql"
],
"homepage": "https://github.com/kenoxa/svelkit#readme",
"bugs": {
"url": "https://github.com/kenoxa/svelkit/issues"
},
"repository": {
"type": "git",
"url": "git+https://github.com/kenoxa/svelkit.git",
"directory": "packages/graphql"
},
"license": "MIT",
"author": "Sascha Tandel <s.tandel@kenoxa.de>",
"scripts": {
"build": "nps build",
"format": "nps format",
"prepublishOnly": "nps test doctoc.readme build",
"test": "nps test",
"typedoc": "typedoc"
},
"jest": {
"preset": "@carv/snowpack-scripts"
},
"dependencies": {
"plain-tag": "^0.1.2"
},
"devDependencies": {
"@types/node-fetch": "^2.5.7",
"cross-fetch": "^3.0.5",
"fetch-mock-jest": "^1.3.0",
"node-fetch": "^2.6.0",
"nps": "^5.9.12",
"svelte-fragment-component": "^1.2.0",
"typedoc": "0.17.0-3"
},
"peerDependencies": {
"svelte": "3.x"
},
"publishConfig": {
"access": "public"
},
"snowpack": {
"extends": "@carv/snowpack-scripts"
}
}
41 changes: 41 additions & 0 deletions packages/graphql/src/client.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import 'cross-fetch/polyfill'
import fetchMock from 'fetch-mock-jest'
import { Client } from './client'
import { toPromise } from './internal/to-promise'
import { minimize } from './internal/minimize'

beforeEach(() => {
fetchMock.mockReset()
})

test('basic query', async () => {
const url = 'http://test.local/graphql'
const query = `query {
hero(episode: $episode) {
name
heroFriends: friends {
id
name
}
}
}`
const variables = { episode: 10 }

fetchMock.post(url, { data: { hero: [] } })

const client = new Client({ url })

const result = await toPromise(client.request(query, variables))

expect(result).toMatchObject({
fetching: false,
data: { hero: [] },
error: undefined,
})

expect(fetchMock.lastOptions(url)).toMatchObject({
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query: minimize(query), variables }),
})
})
142 changes: 142 additions & 0 deletions packages/graphql/src/client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
import { Readable, derived } from 'svelte/store'
import { writable } from 'svelte/store'
import { setContext, getContext } from 'svelte'

import type {
GraphQLVariables,
GraphQLRequestOptions,
GraphQLServerResult,
GraphQLError,
GraphQLClientError,
GraphQLRequest,
GraphQLResponse,
GraphQLExtensions,
GraphQLClient,
GraphQLExchange,
GraphQLNetworkError,
} from './types'
import { getOperation } from './internal/get-operation'
import { fetch, defaultExchanges } from './exchanges'

/* eslint-disable @typescript-eslint/no-explicit-any */

class ClientError extends Error implements GraphQLClientError {
readonly name: GraphQLClientError['name']
readonly errors: ReadonlyArray<GraphQLError>
readonly extensions?: GraphQLExtensions

constructor(errors: GraphQLError[], extensions?: GraphQLExtensions) {
super(errors?.[0]?.message || `GraphQL Error`)
this.name = 'GraphQLClientError'
this.errors = errors
this.extensions = extensions
}
}

const fromServerResult = <T>({
fetching,
error,
data,
errors,
extensions,
}: StoreData<T>): GraphQLResponse<T> => ({
fetching: Boolean(fetching),
data,
error: error || (errors && new ClientError(errors, extensions)),
extensions,
})

interface StoreData<T> extends GraphQLServerResult<T> {
readonly fetching?: boolean
readonly error?: GraphQLNetworkError
}

export interface GraphQLClientOptions extends GraphQLRequestOptions {
/** Setting this will add the fetch exchange */
readonly url?: string

/** Defaults to the default exchanges */
readonly exchanges?: (null | undefined | false | GraphQLExchange)[]
}

export class Client implements GraphQLClient {
private lastId = 0
private exchanges: GraphQLExchange[]
private options: GraphQLRequestOptions

constructor({ url, exchanges = defaultExchanges, ...options }: GraphQLClientOptions) {
if (url) exchanges = [...exchanges, fetch(url)]

this.exchanges = exchanges.filter(Boolean) as GraphQLExchange[]
this.options = options
}

request<T = any, V extends GraphQLVariables = GraphQLVariables>(
query: string,
variables: V,
options: GraphQLRequestOptions = {},
): Readable<GraphQLResponse<T>> {
const store = writable<StoreData<T>>({}, (set) => {
const controller = new AbortController()

set({ fetching: true })

const callExchange = (
request: GraphQLRequest,
index: number,
): Promise<GraphQLServerResult> => {
const exchange = this.exchanges[index]

if (exchange) {
return exchange(
request,
(nextRequest) => callExchange(nextRequest || request, index + 1),
store.update,
)
}

// Terminator
throw new Error(
`No exchange has handled operations of type "${request.operation.type}". Check whether you've added an exchange responsible for these operations.`,
)
}

// eslint-disable-next-line promise/catch-or-return, @typescript-eslint/no-floating-promises
callExchange(
{
query,
variables,
operation: {
id: ++this.lastId,
...getOperation(query),
},
options: {
...this.options,
...options,
headers: { ...this.options.headers, ...options.headers },
signal: controller.signal,
},
},
0,
)
.catch((error: Error) => ({ error }))
.then((result) => store.set({ ...result, fetching: false }))

return () => controller.abort()
})

return derived(store, fromServerResult)
}
}

const CLIENT_CONTEXT_KEY = Symbol.for('@carv/runtime/graphql')

export const initGraphQLClient = (options: GraphQLClientOptions): GraphQLClient => {
const client = new Client(options)
setContext(CLIENT_CONTEXT_KEY, client)
return client
}

export const useGraphQLClient = (): GraphQLClient => getContext(CLIENT_CONTEXT_KEY) as GraphQLClient

/* eslint-enable @typescript-eslint/no-explicit-any */
Loading

0 comments on commit 2016bee

Please sign in to comment.