@operato/graphql 0.2.51

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.editorconfig ADDED
@@ -0,0 +1,29 @@
1
+ # EditorConfig helps developers define and maintain consistent
2
+ # coding styles between different editors and IDEs
3
+ # editorconfig.org
4
+
5
+ root = true
6
+
7
+
8
+ [*]
9
+
10
+ # Change these settings to your own preference
11
+ indent_style = space
12
+ indent_size = 2
13
+
14
+ # We recommend you to keep these unchanged
15
+ end_of_line = lf
16
+ charset = utf-8
17
+ trim_trailing_whitespace = true
18
+ insert_final_newline = true
19
+
20
+ [*.md]
21
+ trim_trailing_whitespace = false
22
+
23
+ [*.json]
24
+ indent_size = 2
25
+
26
+ [*.{html,js,md}]
27
+ block_comment_start = /**
28
+ block_comment = *
29
+ block_comment_end = */
@@ -0,0 +1,3 @@
1
+ module.exports = {
2
+ stories: ['../dist/stories/**/*.stories.{js,md,mdx}'],
3
+ };
@@ -0,0 +1,8 @@
1
+ import { storybookPlugin } from '@web/dev-server-storybook';
2
+ import baseConfig from '../web-dev-server.config.mjs';
3
+
4
+ export default /** @type {import('@web/dev-server').DevServerConfig} */ ({
5
+ ...baseConfig,
6
+ open: '/',
7
+ plugins: [storybookPlugin({ type: 'web-components' }), ...baseConfig.plugins],
8
+ });
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2021 graphql-client
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,76 @@
1
+ # \<graphql-client>
2
+
3
+ This webcomponent follows the [open-wc](https://github.com/open-wc/open-wc) recommendation.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm i graphql-client
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```html
14
+ <script type="module">
15
+ import 'graphql-client/graphql-client.js';
16
+ </script>
17
+
18
+ <graphql-client></graphql-client>
19
+ ```
20
+
21
+ ## Linting and formatting
22
+
23
+ To scan the project for linting and formatting errors, run
24
+
25
+ ```bash
26
+ npm run lint
27
+ ```
28
+
29
+ To automatically fix linting and formatting errors, run
30
+
31
+ ```bash
32
+ npm run format
33
+ ```
34
+
35
+ ## Testing with Web Test Runner
36
+
37
+ To execute a single test run:
38
+
39
+ ```bash
40
+ npm run test
41
+ ```
42
+
43
+ To run the tests in interactive watch mode run:
44
+
45
+ ```bash
46
+ npm run test:watch
47
+ ```
48
+
49
+ ## Demoing with Storybook
50
+
51
+ To run a local instance of Storybook for your component, run
52
+
53
+ ```bash
54
+ npm run storybook
55
+ ```
56
+
57
+ To build a production version of Storybook, run
58
+
59
+ ```bash
60
+ npm run storybook:build
61
+ ```
62
+
63
+
64
+ ## Tooling configs
65
+
66
+ For most of the tools, the configuration is in the `package.json` to reduce the amount of files in your project.
67
+
68
+ If you customize the configuration a lot, you can consider moving them to individual files.
69
+
70
+ ## Local Demo with `web-dev-server`
71
+
72
+ ```bash
73
+ npm start
74
+ ```
75
+
76
+ To run a local development server that serves the basic demo located in `demo/index.html`
@@ -0,0 +1,29 @@
1
+ <!doctype html>
2
+ <html lang="en-GB">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <style>
6
+ body {
7
+ background: #fafafa;
8
+ }
9
+ </style>
10
+ </head>
11
+ <body>
12
+ <div id="demo"></div>
13
+
14
+ <script type="module">
15
+ import { html, render } from 'lit';
16
+ import '../dist/src/graphql-client.js';
17
+
18
+ const title = 'Hello owc World!';
19
+ render(
20
+ html`
21
+ <graphql-client .title=${title}>
22
+ some light-dom
23
+ </graphql-client>
24
+ `,
25
+ document.querySelector('#demo')
26
+ );
27
+ </script>
28
+ </body>
29
+ </html>
@@ -0,0 +1,4 @@
1
+ export * from './gql-context';
2
+ export * from './graphql-client';
3
+ export * from 'json-to-graphql-query';
4
+ //# sourceMappingURL=index.js.map
package/package.json ADDED
@@ -0,0 +1,99 @@
1
+ {
2
+ "name": "@operato/graphql",
3
+ "description": "Webcomponent graphql-client following open-wc recommendations",
4
+ "license": "MIT",
5
+ "author": "heartyoh@hatiolab.com",
6
+ "version": "0.2.51",
7
+ "main": "dist/src/index.js",
8
+ "module": "dist/src/index.js",
9
+ "publishConfig": {
10
+ "access": "public",
11
+ "@operato:registry": "https://registry.npmjs.org"
12
+ },
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/hatiolab/operato.git",
16
+ "directory": "webcomponents/graphql"
17
+ },
18
+ "exports": {
19
+ ".": "./dist/src/index.js",
20
+ "./graphql-client.js": "./dist/src/graphql-client.js"
21
+ },
22
+ "scripts": {
23
+ "analyze": "cem analyze --litelement",
24
+ "start": "tsc && concurrently -k -r \"tsc --watch --preserveWatchOutput\" \"wds\"",
25
+ "build": "tsc && npm run analyze -- --exclude dist",
26
+ "prepublish": "tsc && npm run analyze -- --exclude dist",
27
+ "lint": "eslint --ext .ts,.html . --ignore-path .gitignore && prettier \"**/*.ts\" --check --ignore-path .gitignore",
28
+ "format": "eslint --ext .ts,.html . --fix --ignore-path .gitignore && prettier \"**/*.ts\" --write --ignore-path .gitignore",
29
+ "test": "tsc && wtr --coverage",
30
+ "test:watch": "tsc && concurrently -k -r \"tsc --watch --preserveWatchOutput\" \"wtr --watch\"",
31
+ "storybook": "tsc && npm run analyze -- --exclude dist && concurrently -k -r \"tsc --watch --preserveWatchOutput\" \"wds -c .storybook/server.mjs\"",
32
+ "storybook:build": "tsc && npm run analyze -- --exclude dist && build-storybook"
33
+ },
34
+ "dependencies": {
35
+ "@apollo/client": "^3.5.6",
36
+ "apollo-upload-client": "^17.0.0",
37
+ "graphql-tag": "^2.12.6",
38
+ "json-to-graphql-query": "^2.1.0",
39
+ "lit": "^2.0.2",
40
+ "subscriptions-transport-ws": "^0.11.0"
41
+ },
42
+ "devDependencies": {
43
+ "@custom-elements-manifest/analyzer": "^0.4.17",
44
+ "@hatiolab/prettier-config": "^1.0.0",
45
+ "@open-wc/eslint-config": "^4.3.0",
46
+ "@open-wc/testing": "next",
47
+ "@types/apollo-upload-client": "^14.1.0",
48
+ "@typescript-eslint/eslint-plugin": "^4.33.0",
49
+ "@typescript-eslint/parser": "^4.33.0",
50
+ "@web/dev-server": "^0.1.28",
51
+ "@web/dev-server-storybook": "next",
52
+ "@web/test-runner": "next",
53
+ "concurrently": "^5.3.0",
54
+ "eslint": "^7.32.0",
55
+ "eslint-config-prettier": "^8.3.0",
56
+ "husky": "^4.3.8",
57
+ "lint-staged": "^10.5.4",
58
+ "prettier": "^2.4.1",
59
+ "tslib": "^2.3.1",
60
+ "typescript": "^4.5.2"
61
+ },
62
+ "customElements": "custom-elements.json",
63
+ "eslintConfig": {
64
+ "parser": "@typescript-eslint/parser",
65
+ "extends": [
66
+ "@open-wc",
67
+ "prettier"
68
+ ],
69
+ "plugins": [
70
+ "@typescript-eslint"
71
+ ],
72
+ "rules": {
73
+ "no-unused-vars": "off",
74
+ "@typescript-eslint/no-unused-vars": [
75
+ "error"
76
+ ],
77
+ "import/no-unresolved": "off",
78
+ "import/extensions": [
79
+ "error",
80
+ "always",
81
+ {
82
+ "ignorePackages": true
83
+ }
84
+ ]
85
+ }
86
+ },
87
+ "prettier": "@hatiolab/prettier-config",
88
+ "husky": {
89
+ "hooks": {
90
+ "pre-commit": "lint-staged"
91
+ }
92
+ },
93
+ "lint-staged": {
94
+ "*.ts": [
95
+ "eslint --fix",
96
+ "prettier --write"
97
+ ]
98
+ }
99
+ }
@@ -0,0 +1,23 @@
1
+ export const CONTEXT_KEY = '__context__'
2
+
3
+ export function gqlContext() {
4
+ const search = new URLSearchParams(location.search)
5
+ return JSON.parse(search.get(CONTEXT_KEY) || '""') || ''
6
+ }
7
+
8
+ export function buildGqlContext(
9
+ context:
10
+ | {
11
+ headers: {
12
+ 'x-things-factory-domain': string
13
+ }
14
+ }
15
+ | string
16
+ ) {
17
+ if (!context) throw new Error('context is not passed')
18
+ if (typeof context !== 'string') {
19
+ context = JSON.stringify(context)
20
+ }
21
+
22
+ return new URLSearchParams({ [CONTEXT_KEY]: context as string }).toString()
23
+ }
@@ -0,0 +1,179 @@
1
+ import { ApolloClient, ApolloLink, DefaultOptions, HttpLink, InMemoryCache, from } from '@apollo/client/core'
2
+
3
+ import { ErrorLink } from '@apollo/client/link/error'
4
+ import { ServerParseError } from '@apollo/client'
5
+ import { SubscriptionClient } from 'subscriptions-transport-ws'
6
+ import { createUploadLink } from 'apollo-upload-client'
7
+ import { onError } from '@apollo/client/link/error'
8
+
9
+ // import { persistCache } from 'apollo-cache-persist'
10
+
11
+ export const GRAPHQL_URI = '/graphql'
12
+
13
+ const defaultOptions: DefaultOptions = {
14
+ watchQuery: {
15
+ fetchPolicy: 'no-cache',
16
+ errorPolicy: 'ignore'
17
+ },
18
+ query: {
19
+ fetchPolicy: 'no-cache', //'network-only'
20
+ errorPolicy: 'all'
21
+ },
22
+ mutate: {
23
+ errorPolicy: 'all'
24
+ }
25
+ }
26
+
27
+ const ERROR_HANDLER: ErrorLink.ErrorHandler = ({ operation, graphQLErrors, networkError }) => {
28
+ if (graphQLErrors) {
29
+ document.dispatchEvent(
30
+ new CustomEvent('notify', {
31
+ detail: {
32
+ level: 'error',
33
+ message: graphQLErrors[0].message,
34
+ ex: graphQLErrors
35
+ }
36
+ })
37
+ )
38
+ }
39
+
40
+ if (networkError) {
41
+ /* networkError가 ServerParseError 이거나 ServerError 인 경우에만 statusCode를 갖는다. */
42
+ switch ((networkError as ServerParseError).statusCode) {
43
+ case undefined /* in case this error is not a server side error */:
44
+ document.dispatchEvent(
45
+ new CustomEvent('notify', {
46
+ detail: {
47
+ level: 'error',
48
+ message: networkError.message,
49
+ ex: networkError
50
+ }
51
+ })
52
+ )
53
+ break
54
+
55
+ case 401:
56
+ /* 401 에러가 리턴되면, 인증이 필요하다는 메시지를 dispatch 한다. 이 auth 모듈 등에서 이 메시지를 받아서 signin 프로세스를 진행할 수 있다. */
57
+ document.dispatchEvent(new CustomEvent('auth-required'))
58
+ break
59
+
60
+ case 403:
61
+ /* 403 에러가 리턴되면, 도메인 정보가 필요하다는 메시지를 dispatch 한다. 이 auth 모듈 등에서 이 메시지를 받아서 domain-register 프로세스 등을 진행할 수 있다. */
62
+ document.dispatchEvent(new CustomEvent('domain-required'))
63
+ break
64
+
65
+ default:
66
+ var { name, response, statusCode, bodyText, message } = networkError as ServerParseError
67
+ if (name == 'ServerParseError') {
68
+ message = `[ ${statusCode || ''} : ${response.statusText} ] ${bodyText}`
69
+ } else {
70
+ /* in case this error is instanceof ServerError */
71
+ message = `[ ${statusCode || ''} : ${response.statusText} ] ${message}`
72
+ }
73
+
74
+ document.dispatchEvent(
75
+ new CustomEvent('notify', {
76
+ detail: {
77
+ level: 'error',
78
+ message,
79
+ ex: networkError
80
+ }
81
+ })
82
+ )
83
+ }
84
+ }
85
+ }
86
+
87
+ const cache = new InMemoryCache({
88
+ addTypename: false
89
+ // dataIdFromObject: object => object.key
90
+ })
91
+
92
+ const httpOptions = {
93
+ GRAPHQL_URI,
94
+ credentials: 'include'
95
+ }
96
+
97
+ const httpLink = ApolloLink.split(
98
+ operation => operation.getContext().hasUpload,
99
+ createUploadLink(httpOptions),
100
+ new HttpLink(httpOptions)
101
+ )
102
+
103
+ // const initPersistCache = async () => {
104
+ // persistCache({
105
+ // cache,
106
+ // storage: window.localStorage
107
+ // })
108
+ // }
109
+
110
+ // initPersistCache()
111
+
112
+ export const client = new ApolloClient({
113
+ defaultOptions,
114
+ cache,
115
+ link: from([onError(ERROR_HANDLER), httpLink])
116
+ })
117
+
118
+ /* SubscriptionClient */
119
+ var subscriptionClient: Promise<SubscriptionClient> | null
120
+
121
+ const getSubscriptionClient = async (): Promise<SubscriptionClient> => {
122
+ if (!subscriptionClient) {
123
+ subscriptionClient = new Promise((resolve, reject) => {
124
+ var client = new SubscriptionClient(location.origin.replace(/^http/, 'ws') + '/subscriptions', {
125
+ reconnect: true,
126
+ connectionParams: {
127
+ headers: {
128
+ /*
129
+ 특정 도메인의 데이타만 받고자 하는 경우에, referer 정보를 제공해서 서버에서 서브도메인 정보를 취득하도록 한다.
130
+ referer: location.href
131
+ 또는, 이미 서브도메인 정보를 알고 있다면,
132
+ 'x-things-factory-domain': '[subdomain]'
133
+ 을 보낼 수 있다.
134
+ 관련 정보를 보내지 않는다면, 사용자가 권한을 가진 모든 도메인의 데이타를 수신하게 된다.
135
+ */
136
+ referer: location.href
137
+ }
138
+ }
139
+ })
140
+
141
+ client.onError(err => {
142
+ //readyState === 3 인 경우 url을 잘 못 입력했거나, 서버에 문제가 있는 경우이므로 강제로 close() 시킨다.
143
+ if (client.status === 3) {
144
+ client.close()
145
+ }
146
+ reject(err)
147
+ })
148
+
149
+ client.onConnected(() => {
150
+ resolve(client)
151
+ })
152
+ })
153
+ }
154
+
155
+ return await subscriptionClient
156
+ }
157
+
158
+ var subscriptions: (() => void)[] = []
159
+
160
+ export const subscribe = async (request: any, subscribe: any) => {
161
+ var client = await getSubscriptionClient()
162
+ var { unsubscribe } = client.request(request).subscribe(subscribe)
163
+
164
+ subscriptions.push(unsubscribe)
165
+
166
+ return {
167
+ unsubscribe() {
168
+ subscriptions.splice(subscriptions.indexOf(unsubscribe), 1)
169
+ unsubscribe()
170
+
171
+ if (subscriptions.length == 0) {
172
+ client.unsubscribeAll()
173
+ client.close(true)
174
+
175
+ subscriptionClient = null
176
+ }
177
+ }
178
+ }
179
+ }
package/src/index.ts ADDED
@@ -0,0 +1,3 @@
1
+ export * from './gql-context'
2
+ export * from './graphql-client'
3
+ export * from 'json-to-graphql-query'
package/tsconfig.json ADDED
@@ -0,0 +1,22 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "es2018",
4
+ "module": "esnext",
5
+ "moduleResolution": "node",
6
+ "noEmitOnError": true,
7
+ "lib": ["es2017", "dom"],
8
+ "strict": true,
9
+ "esModuleInterop": false,
10
+ "allowSyntheticDefaultImports": true,
11
+ "experimentalDecorators": true,
12
+ "importHelpers": true,
13
+ "outDir": "dist",
14
+ "sourceMap": true,
15
+ "inlineSources": true,
16
+ "rootDir": "./",
17
+ "declaration": true,
18
+ "incremental": true,
19
+ "types": ["node", "mocha", "@apollo/client"]
20
+ },
21
+ "include": ["**/*.ts"]
22
+ }
@@ -0,0 +1,27 @@
1
+ // import { hmrPlugin, presets } from '@open-wc/dev-server-hmr';
2
+
3
+ /** Use Hot Module replacement by adding --hmr to the start command */
4
+ const hmr = process.argv.includes('--hmr');
5
+
6
+ export default /** @type {import('@web/dev-server').DevServerConfig} */ ({
7
+ open: '/demo/',
8
+ /** Use regular watch mode if HMR is not enabled. */
9
+ watch: !hmr,
10
+ /** Resolve bare module imports */
11
+ nodeResolve: {
12
+ exportConditions: ['browser', 'development'],
13
+ },
14
+
15
+ /** Compile JS for older browsers. Requires @web/dev-server-esbuild plugin */
16
+ // esbuildTarget: 'auto'
17
+
18
+ /** Set appIndex to enable SPA routing */
19
+ // appIndex: 'demo/index.html',
20
+
21
+ plugins: [
22
+ /** Use Hot Module Replacement by uncommenting. Requires @open-wc/dev-server-hmr plugin */
23
+ // hmr && hmrPlugin({ exclude: ['**/*/node_modules/**/*'], presets: [presets.litElement] }),
24
+ ],
25
+
26
+ // See documentation for all available options
27
+ });
@@ -0,0 +1,41 @@
1
+ // import { playwrightLauncher } from '@web/test-runner-playwright';
2
+
3
+ const filteredLogs = ['Running in dev mode', 'lit-html is in dev mode'];
4
+
5
+ export default /** @type {import("@web/test-runner").TestRunnerConfig} */ ({
6
+ /** Test files to run */
7
+ files: 'dist/test/**/*.test.js',
8
+
9
+ /** Resolve bare module imports */
10
+ nodeResolve: {
11
+ exportConditions: ['browser', 'development'],
12
+ },
13
+
14
+ /** Filter out lit dev mode logs */
15
+ filterBrowserLogs(log) {
16
+ for (const arg of log.args) {
17
+ if (typeof arg === 'string' && filteredLogs.some(l => arg.includes(l))) {
18
+ return false;
19
+ }
20
+ }
21
+ return true;
22
+ },
23
+
24
+ /** Compile JS for older browsers. Requires @web/dev-server-esbuild plugin */
25
+ // esbuildTarget: 'auto',
26
+
27
+ /** Amount of browsers to run concurrently */
28
+ // concurrentBrowsers: 2,
29
+
30
+ /** Amount of test files per browser to test concurrently */
31
+ // concurrency: 1,
32
+
33
+ /** Browsers to run tests on */
34
+ // browsers: [
35
+ // playwrightLauncher({ product: 'chromium' }),
36
+ // playwrightLauncher({ product: 'firefox' }),
37
+ // playwrightLauncher({ product: 'webkit' }),
38
+ // ],
39
+
40
+ // See documentation for all available options
41
+ });