Explorar el Código

chore(server): Use graphql-code-generator for generating all types

Michael Bromley hace 7 años
padre
commit
10e985af8d

+ 2 - 2
admin-ui/src/app/data/client-state/client-types.graphql

@@ -1,10 +1,10 @@
-extend type Query {
+type Query {
     networkStatus: NetworkStatus!
     userStatus: UserStatus!
     uiState: UiState!
 }
 
-extend type Mutation {
+type Mutation {
     requestStarted: Int!
     requestCompleted: Int!
     setAsLoggedIn(username: String!, loginTime: String!): UserStatus!

+ 30 - 0
codegen/client-schema.ts

@@ -0,0 +1,30 @@
+import * as fs from 'fs';
+import { makeExecutableSchema } from 'graphql-tools';
+import * as path from 'path';
+
+const CLIENT_SCHEMA_FILE = '../admin-ui/src/app/data/client-state/client-types.graphql';
+const LANGUAGE_CODE_FILE = '../server/src/common/types/language-code.graphql';
+
+function loadGraphQL(file: string): string {
+  const filePath = path.join(__dirname, file);
+  return fs.readFileSync(filePath, 'utf8');
+}
+
+/**
+ * Augments the client schema (used by apollo-link-state) with missing
+ * definitions, to allow the codegen step to work correctly.
+ * See: https://github.com/dotansimha/graphql-code-generator/issues/583
+ */
+function getClientSchema() {
+    const clientDirective = `
+        directive @client on FIELD
+    `;
+    const clientSchemaString = loadGraphQL(CLIENT_SCHEMA_FILE);
+    const languageCodeString = loadGraphQL(LANGUAGE_CODE_FILE);
+    const schema = makeExecutableSchema({
+        typeDefs: [clientSchemaString, clientDirective, languageCodeString],
+    });
+    return schema;
+}
+
+export default getClientSchema();

+ 45 - 0
codegen/download-introspection-schema.ts

@@ -0,0 +1,45 @@
+import * as fs from 'fs';
+import { introspectionQuery } from 'graphql';
+import * as http from 'http';
+import * as path from 'path';
+
+import { API_PATH, API_PORT } from '../shared/shared-constants';
+
+// tslint:disable:no-console
+
+/**
+ * Makes an introspection query to the Vendure server and writes the result to a
+ * schema.json file.
+ *
+ * If there is an error connecting to the server, the promise resolves to false.
+ */
+export function downloadIntrospectionSchema(outputFilePath: string): Promise<boolean> {
+    const body = JSON.stringify({ query: introspectionQuery });
+
+    return new Promise((resolve, reject) => {
+        const request = http.request({
+            method: 'post',
+            host: 'localhost',
+            port: API_PORT,
+            path: '/' + API_PATH,
+            headers: {
+                'Content-Type': 'application/json',
+                'Content-Length': Buffer.byteLength(body),
+            },
+        }, response => {
+            const outputFile = fs.createWriteStream(outputFilePath);
+            response.pipe(outputFile);
+            response.on('end', () => resolve(true));
+            response.on('error', reject);
+        });
+        request.write(body);
+        request.end();
+        request.on('error', (err: any) => {
+            if (err.code === 'ECONNREFUSED') {
+                console.error(`ERROR: Could not connect to the Vendure server at http://localhost:${API_PORT}/${API_PATH}`);
+                resolve(false);
+            }
+            reject(err);
+        });
+    });
+}

+ 33 - 0
codegen/generate-graphql-types.ts

@@ -0,0 +1,33 @@
+import { generate } from 'graphql-code-generator';
+import * as path from 'path';
+
+import { API_PATH, API_PORT } from '../shared/shared-constants';
+
+import { downloadIntrospectionSchema } from './download-introspection-schema';
+
+const CLIENT_QUERY_FILES = path.join(__dirname, '../admin-ui/src/app/data/definitions/*.ts');
+const SCHEMA_OUTPUT_FILE = path.join(__dirname, '../schema.json');
+
+// tslint:disable:no-console
+
+downloadIntrospectionSchema(SCHEMA_OUTPUT_FILE)
+    .then((downloaded) => {
+        if (!downloaded) {
+            console.log('Attempting to generate types from existing schema.json...');
+        }
+        return generate({
+            schema: SCHEMA_OUTPUT_FILE,
+            clientSchema: path.join(__dirname, 'client-schema.ts'),
+            template: 'typescript',
+            out: path.join(__dirname,  '../shared/'),
+            overwrite: true,
+            args: [CLIENT_QUERY_FILES],
+        });
+    })
+    .then(result => {
+            process.exit(0);
+        },
+        err => {
+            console.error(err);
+            process.exit(1);
+        });

+ 5 - 0
package.json

@@ -4,6 +4,7 @@
   "scripts": {
     "apollo": "apollo",
     "generate-gql-types": "ts-node generate-graphql-types.ts",
+    "generate-gql-types2": "ts-node ./codegen/generate-graphql-types.ts",
     "postinstall": "cd admin-ui && yarn && cd ../server && yarn",
     "test": "cd admin-ui && yarn test --watch=false --browsers=ChromeHeadlessCI --progress=false && cd ../server && yarn test && yarn test:e2e",
     "format": "prettier --write",
@@ -15,6 +16,10 @@
   },
   "devDependencies": {
     "apollo": "^1.7.1",
+    "graphql": "^14.0.2",
+    "graphql-code-generator": "^0.12.6",
+    "graphql-codegen-typescript-template": "^0.12.6",
+    "graphql-tools": "^4.0.0",
     "husky": "^0.14.3",
     "lint-staged": "^7.2.0",
     "prettier": "^1.13.7",

La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 0 - 0
schema.json


La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 576 - 13
yarn.lock


Algunos archivos no se mostraron porque demasiados archivos cambiaron en este cambio