@ttoss/graphql-api 0.1.0

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.
@@ -0,0 +1,10 @@
1
+ import { SchemaComposer } from 'graphql-compose';
2
+ import Koa from 'koa';
3
+ export { default as Router } from '@koa/router';
4
+
5
+ declare const createServer: ({ schemaComposer, graphiql, }: {
6
+ schemaComposer: SchemaComposer<any>;
7
+ graphiql?: boolean | undefined;
8
+ }) => Koa;
9
+
10
+ export { createServer };
package/dist/server.js ADDED
@@ -0,0 +1,90 @@
1
+ /** Powered by @ttoss/config. https://ttoss.dev/docs/modules/packages/config/ */
2
+ "use strict";
3
+
4
+ var __create = Object.create;
5
+ var __defProp = Object.defineProperty;
6
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
7
+ var __getOwnPropNames = Object.getOwnPropertyNames;
8
+ var __getProtoOf = Object.getPrototypeOf;
9
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
10
+ var __export = (target, all) => {
11
+ for (var name in all) __defProp(target, name, {
12
+ get: all[name],
13
+ enumerable: true
14
+ });
15
+ };
16
+ var __copyProps = (to, from, except, desc) => {
17
+ if (from && typeof from === "object" || typeof from === "function") {
18
+ for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
19
+ get: () => from[key],
20
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
21
+ });
22
+ }
23
+ return to;
24
+ };
25
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
26
+ // If the importer is in node compatibility mode or this is not an ESM
27
+ // file that has been converted to a CommonJS file using a Babel-
28
+ // compatible transform (i.e. "__esModule" has not been set), then set
29
+ // "default" to the CommonJS "module.exports" for node compatibility.
30
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
31
+ value: mod,
32
+ enumerable: true
33
+ }) : target, mod));
34
+ var __toCommonJS = mod => __copyProps(__defProp({}, "__esModule", {
35
+ value: true
36
+ }), mod);
37
+
38
+ // src/server.ts
39
+ var server_exports = {};
40
+ __export(server_exports, {
41
+ Router: () => import_router.default,
42
+ createServer: () => createServer
43
+ });
44
+ module.exports = __toCommonJS(server_exports);
45
+ var import_graphql_helix = require("graphql-helix");
46
+ var import_koa = __toESM(require("koa"));
47
+ var import_router = __toESM(require("@koa/router"));
48
+ var import_koa_bodyparser = __toESM(require("koa-bodyparser"));
49
+ var createServer = ({
50
+ schemaComposer,
51
+ graphiql = false
52
+ }) => {
53
+ const server = new import_koa.default();
54
+ const router = new import_router.default();
55
+ server.use((0, import_koa_bodyparser.default)());
56
+ router.all("/graphql", async ctx => {
57
+ const request = {
58
+ body: ctx.request.body,
59
+ headers: ctx.headers,
60
+ method: ctx.method,
61
+ query: ctx.request.query
62
+ };
63
+ if ((0, import_graphql_helix.shouldRenderGraphiQL)(request)) {
64
+ if (graphiql) {
65
+ ctx.body = (0, import_graphql_helix.renderGraphiQL)({});
66
+ }
67
+ return;
68
+ }
69
+ const {
70
+ operationName,
71
+ query,
72
+ variables
73
+ } = (0, import_graphql_helix.getGraphQLParameters)(request);
74
+ const result = await (0, import_graphql_helix.processRequest)({
75
+ operationName,
76
+ query,
77
+ variables,
78
+ request,
79
+ schema: schemaComposer.buildSchema()
80
+ });
81
+ (0, import_graphql_helix.sendResult)(result, ctx.res);
82
+ });
83
+ server.use(router.routes()).use(router.allowedMethods());
84
+ return server;
85
+ };
86
+ // Annotate the CommonJS export names for ESM import in node:
87
+ 0 && (module.exports = {
88
+ Router,
89
+ createServer
90
+ });
package/package.json ADDED
@@ -0,0 +1,76 @@
1
+ {
2
+ "name": "@ttoss/graphql-api",
3
+ "version": "0.1.0",
4
+ "description": "A library for building GraphQL APIs.",
5
+ "author": "ttoss",
6
+ "contributors": [
7
+ "Pedro Arantes <pedro@arantespp.com> (https://arantespp.com)"
8
+ ],
9
+ "exports": {
10
+ ".": {
11
+ "import": "./dist/esm/index.js",
12
+ "require": "./dist/index.js"
13
+ },
14
+ "./server": {
15
+ "import": "./dist/esm/server.js",
16
+ "require": "./dist/server.js"
17
+ }
18
+ },
19
+ "main": "dist/index.js",
20
+ "module": "dist/esm/index.js",
21
+ "bin": {
22
+ "ttoss-graphql-api": "./bin/cli.js"
23
+ },
24
+ "files": [
25
+ "dist",
26
+ "src"
27
+ ],
28
+ "sideEffects": false,
29
+ "typings": "dist/index.d.ts",
30
+ "dependencies": {
31
+ "@koa/router": "^12.0.0",
32
+ "graphql-compose-connection": "^8.2.1",
33
+ "graphql-helix": "^1.13.0",
34
+ "koa": "^2.14.2",
35
+ "koa-bodyparser": "^4.4.0",
36
+ "npmlog": "^7.0.1",
37
+ "ts-node": "^10.9.1",
38
+ "yargs": "^17.7.2"
39
+ },
40
+ "peerDependencies": {
41
+ "graphql": "^16.6.0",
42
+ "graphql-compose": "^9.0.10"
43
+ },
44
+ "devDependencies": {
45
+ "@types/koa": "^2.13.6",
46
+ "@types/koa__router": "^12.0.0",
47
+ "@types/koa-bodyparser": "^4.3.10",
48
+ "@types/yargs": "^17.0.24",
49
+ "graphql": "^16.6.0",
50
+ "graphql-compose": "^9.0.10",
51
+ "jest": "^29.5.0",
52
+ "tsup": "^6.7.0",
53
+ "@ttoss/config": "^1.30.0"
54
+ },
55
+ "keywords": [
56
+ "api",
57
+ "graphql"
58
+ ],
59
+ "publishConfig": {
60
+ "access": "public"
61
+ },
62
+ "typesVersions": {
63
+ "*": {
64
+ ".": [
65
+ "./dist/index.d.ts"
66
+ ],
67
+ "server": [
68
+ "./dist/server.d.ts"
69
+ ]
70
+ }
71
+ },
72
+ "scripts": {
73
+ "build": "tsup",
74
+ "test": "jest"
75
+ }
76
+ }
package/src/cli.ts ADDED
@@ -0,0 +1,35 @@
1
+ import * as fs from 'fs';
2
+ import * as path from 'path';
3
+ import { register } from 'ts-node';
4
+ import log from 'npmlog';
5
+ import yargs from 'yargs';
6
+
7
+ const logPrefix = 'graphql-api';
8
+
9
+ register({
10
+ transpileOnly: true,
11
+ });
12
+
13
+ const argv: any = yargs(process.argv.slice(2)).argv;
14
+
15
+ if (argv._.includes('build-schema')) {
16
+ log.info(logPrefix, 'Building schema...');
17
+
18
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
19
+ const { schemaComposer } = require(path.resolve(
20
+ process.cwd(),
21
+ 'src',
22
+ 'schemaComposer.ts'
23
+ ));
24
+
25
+ const sdl = schemaComposer.toSDL();
26
+
27
+ /**
28
+ * Save to schema/schema.graphql. schema folder might not exist.
29
+ */
30
+ fs.mkdirSync('schema', { recursive: true });
31
+
32
+ fs.writeFileSync('schema/schema.graphql', sdl);
33
+
34
+ log.info(logPrefix, 'Schema built.');
35
+ }
@@ -0,0 +1,67 @@
1
+ import { ObjectTypeComposer } from 'graphql-compose';
2
+ import { getNodeFieldConfig } from './nodeFieldConfig';
3
+ import { getNodeInterface } from './nodeInterface';
4
+ import { toGlobalId } from './globalId';
5
+
6
+ // all wrapped typeComposers with Relay, stored in this variable
7
+ // for futher type resolving via NodeInterface.resolveType method
8
+ export const TypeMapForRelayNode: any = {};
9
+
10
+ export const composeWithRelay = <TContext>(
11
+ tc: ObjectTypeComposer<any, TContext>
12
+ ): ObjectTypeComposer<any, TContext> => {
13
+ if (!(tc instanceof ObjectTypeComposer)) {
14
+ throw new Error(
15
+ 'You should provide ObjectTypeComposer instance to composeWithRelay method'
16
+ );
17
+ }
18
+
19
+ const nodeInterface = getNodeInterface(tc.schemaComposer);
20
+ const nodeFieldConfig = getNodeFieldConfig(
21
+ TypeMapForRelayNode,
22
+ nodeInterface
23
+ );
24
+
25
+ if (tc.getTypeName() === 'Query' || tc.getTypeName() === 'RootQuery') {
26
+ tc.setField('node', nodeFieldConfig);
27
+ return tc;
28
+ }
29
+
30
+ if (tc.getTypeName() === 'Mutation' || tc.getTypeName() === 'RootMutation') {
31
+ // just skip
32
+ return tc;
33
+ }
34
+
35
+ if (!tc.hasRecordIdFn()) {
36
+ throw new Error(
37
+ `ObjectTypeComposer(${tc.getTypeName()}) should have recordIdFn. ` +
38
+ 'This function returns ID from provided object.'
39
+ );
40
+ }
41
+
42
+ const findById = tc.getResolver('findById');
43
+ if (!findById) {
44
+ throw new Error(
45
+ `ObjectTypeComposer(${tc.getTypeName()}) provided to composeWithRelay ` +
46
+ 'should have findById resolver.'
47
+ );
48
+ }
49
+ TypeMapForRelayNode[tc.getTypeName()] = {
50
+ resolver: findById,
51
+ tc,
52
+ };
53
+
54
+ tc.addFields({
55
+ id: {
56
+ type: 'ID!',
57
+ description: 'The globally unique ID among all types',
58
+ resolve: (source) => {
59
+ return toGlobalId(tc.getTypeName(), tc.getRecordId(source));
60
+ },
61
+ },
62
+ });
63
+
64
+ tc.addInterface(nodeInterface);
65
+
66
+ return tc;
67
+ };
@@ -0,0 +1,32 @@
1
+ export type Base64String = string;
2
+
3
+ export type ResolvedGlobalId = {
4
+ type: string;
5
+ recordId: string;
6
+ };
7
+
8
+ export const base64 = (i: string): Base64String => {
9
+ return Buffer.from(i, 'ascii').toString('base64');
10
+ };
11
+
12
+ export const unbase64 = (i: Base64String): string => {
13
+ return Buffer.from(i, 'base64').toString('ascii');
14
+ };
15
+
16
+ /**
17
+ * Takes a type name and an ID specific to that type name, and returns a
18
+ * "global ID" that is unique among all types.
19
+ */
20
+ export const toGlobalId = (type: string, recordId: string | number): string => {
21
+ return base64([type, recordId].join(':'));
22
+ };
23
+
24
+ /**
25
+ * Takes the "global ID" created by toGlobalID, and returns the type name and ID
26
+ * used to create it.
27
+ */
28
+ export const fromGlobalId = (globalId: string): ResolvedGlobalId => {
29
+ const unbasedGlobalId = unbase64(globalId);
30
+ const [type, recordId] = unbasedGlobalId.split(':');
31
+ return { type, recordId };
32
+ };
@@ -0,0 +1,7 @@
1
+ import { composeWithRelay } from './composeWithRelay';
2
+ import { schemaComposer } from 'graphql-compose';
3
+
4
+ composeWithRelay(schemaComposer.Query);
5
+
6
+ export { composeWithRelay };
7
+ export { fromGlobalId, toGlobalId } from './globalId';
@@ -0,0 +1,82 @@
1
+ import {
2
+ type InterfaceTypeComposer,
3
+ type ObjectTypeComposerFieldConfigDefinition,
4
+ getProjectionFromAST,
5
+ } from 'graphql-compose';
6
+ import { fromGlobalId } from './globalId';
7
+ import type { GraphQLResolveInfo } from 'graphql-compose/lib/graphql';
8
+ import type { ObjectTypeComposer, Resolver } from 'graphql-compose';
9
+
10
+ export type TypeMapForRelayNode<TSource, TContext> = {
11
+ [typeName: string]: {
12
+ resolver: Resolver<TSource, TContext>;
13
+ tc: ObjectTypeComposer<TSource, TContext>;
14
+ };
15
+ };
16
+
17
+ // this fieldConfig must be set to RootQuery.node field
18
+ export const getNodeFieldConfig = (
19
+ typeMapForRelayNode: TypeMapForRelayNode<any, any>,
20
+ nodeInterface: InterfaceTypeComposer<any, any>
21
+ ): ObjectTypeComposerFieldConfigDefinition<any, any> => {
22
+ return {
23
+ description:
24
+ 'Fetches an object that has globally unique ID among all types',
25
+ type: nodeInterface,
26
+ args: {
27
+ id: {
28
+ type: 'ID!',
29
+ description: 'The globally unique ID among all types',
30
+ },
31
+ },
32
+ resolve: (
33
+ source: any,
34
+ args: { [argName: string]: any },
35
+ context: any,
36
+ info: GraphQLResolveInfo
37
+ ) => {
38
+ if (!args.id || !(typeof args.id === 'string')) {
39
+ return null;
40
+ }
41
+ const { type } = fromGlobalId(args.id);
42
+
43
+ if (!typeMapForRelayNode[type]) {
44
+ return null;
45
+ }
46
+ const { tc, resolver: findById } = typeMapForRelayNode[type];
47
+ if (findById && findById.resolve && tc) {
48
+ const graphqlType = tc.getType();
49
+
50
+ // set `returnType` for proper work of `getProjectionFromAST`
51
+ // it will correctly add required fields for `relation` to `projection`
52
+ let projection;
53
+ if (info) {
54
+ projection = getProjectionFromAST({
55
+ ...info,
56
+ returnType: graphqlType,
57
+ });
58
+ } else {
59
+ projection = {};
60
+ }
61
+
62
+ // suppose that first argument is argument with id field
63
+ const idArgName = Object.keys(findById.args)[0];
64
+ return findById
65
+ .resolve({
66
+ source,
67
+ args: { [idArgName]: args.id }, // eg. mongoose has _id fieldname, so should map
68
+ context,
69
+ info,
70
+ projection,
71
+ })
72
+ .then((res: any) => {
73
+ if (!res) return res;
74
+ res.__nodeType = graphqlType;
75
+ return res;
76
+ });
77
+ }
78
+
79
+ return null;
80
+ },
81
+ };
82
+ };
@@ -0,0 +1,31 @@
1
+ import { InterfaceTypeComposer, type SchemaComposer } from 'graphql-compose';
2
+
3
+ const NodeTC = InterfaceTypeComposer.createTemp({
4
+ name: 'Node',
5
+ description:
6
+ 'An object, that can be fetched by the globally unique ID among all types.',
7
+ fields: {
8
+ id: {
9
+ type: 'ID!',
10
+ description: 'The globally unique ID among all types.',
11
+ },
12
+ },
13
+ resolveType: (payload: any) => {
14
+ // `payload.__nodeType` was added to payload via nodeFieldConfig.resolve
15
+ return payload.__nodeType.name ? payload.__nodeType.name : null;
16
+ },
17
+ });
18
+
19
+ export const NodeInterface = NodeTC.getType();
20
+
21
+ export const getNodeInterface = <TContext>(
22
+ sc: SchemaComposer<TContext>
23
+ ): InterfaceTypeComposer<any, TContext> => {
24
+ if (sc.hasInstance('Node', InterfaceTypeComposer)) {
25
+ return sc.get('Node') as any;
26
+ }
27
+
28
+ sc.set('Node', NodeTC);
29
+
30
+ return NodeTC;
31
+ };
package/src/index.ts ADDED
@@ -0,0 +1,3 @@
1
+ export { composeWithRelay, toGlobalId, fromGlobalId } from './composeWithRelay';
2
+ export { default as composeWithConnection } from 'graphql-compose-connection';
3
+ export * from 'graphql-compose';
package/src/server.ts ADDED
@@ -0,0 +1,60 @@
1
+ import { type SchemaComposer } from 'graphql-compose';
2
+ import {
3
+ getGraphQLParameters,
4
+ processRequest,
5
+ renderGraphiQL,
6
+ sendResult,
7
+ shouldRenderGraphiQL,
8
+ } from 'graphql-helix';
9
+ import Koa from 'koa';
10
+ import Router from '@koa/router';
11
+ import bodyParser from 'koa-bodyparser';
12
+
13
+ export { Router };
14
+
15
+ export const createServer = ({
16
+ schemaComposer,
17
+ graphiql = false,
18
+ }: {
19
+ schemaComposer: SchemaComposer<any>;
20
+ graphiql?: boolean;
21
+ }): Koa => {
22
+ const server = new Koa();
23
+
24
+ const router = new Router();
25
+
26
+ server.use(bodyParser());
27
+
28
+ router.all('/graphql', async (ctx) => {
29
+ const request = {
30
+ body: ctx.request.body,
31
+ headers: ctx.headers,
32
+ method: ctx.method,
33
+ query: ctx.request.query,
34
+ };
35
+
36
+ if (shouldRenderGraphiQL(request)) {
37
+ if (graphiql) {
38
+ ctx.body = renderGraphiQL({});
39
+ }
40
+
41
+ return;
42
+ }
43
+
44
+ const { operationName, query, variables } = getGraphQLParameters(request);
45
+
46
+ const result = await processRequest({
47
+ operationName,
48
+ query,
49
+ variables,
50
+ request,
51
+ schema: schemaComposer.buildSchema(),
52
+ });
53
+
54
+ sendResult(result, ctx.res);
55
+ });
56
+
57
+ server.use(router.routes()).use(router.allowedMethods());
58
+
59
+ return server;
60
+ };