Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(node)!: restructure server imports #497

Merged
merged 21 commits into from Dec 29, 2022
Merged
Show file tree
Hide file tree
Changes from 17 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 3 additions & 0 deletions cli/commands/generate.go
Expand Up @@ -95,6 +95,7 @@ var generateCmd = &cobra.Command{
}
webhooksBundler = bundler.NewBundler(bundler.Config{
Name: "webhooks-bundler",
Production: true,
EntryPoints: webhookPaths,
AbsWorkingDir: wunderGraphDir,
OutDir: webhooksOutDir,
Expand All @@ -108,6 +109,7 @@ var generateCmd = &cobra.Command{

hooksBundler := bundler.NewBundler(bundler.Config{
Name: "server-bundler",
Production: true,
AbsWorkingDir: wunderGraphDir,
EntryPoints: []string{serverEntryPointFilename},
OutFile: serverOutFile,
Expand Down Expand Up @@ -161,6 +163,7 @@ var generateCmd = &cobra.Command{

configBundler := bundler.NewBundler(bundler.Config{
Name: "config-bundler",
Production: true,
AbsWorkingDir: wunderGraphDir,
EntryPoints: []string{configEntryPointFilename},
OutFile: configOutFile,
Expand Down
22 changes: 12 additions & 10 deletions cli/commands/root.go
Expand Up @@ -135,17 +135,19 @@ var rootCmd = &cobra.Command{
metricUsageName := telemetry.UsageMetricSuffix(cmdMetricName)
cmdUsageMetric := telemetry.NewUsageMetric(metricUsageName)

err := TelemetryClient.Send([]telemetry.Metric{cmdUsageMetric})

// AddMetric the usage of the command immediately
if rootFlags.TelemetryDebugMode {
if err != nil {
log.Error("Could not send telemetry data", zap.Error(err))
} else {
log.Info("Telemetry data sent")
// Send telemetry in a goroutine to not block the command
go func() {
err := TelemetryClient.Send([]telemetry.Metric{cmdUsageMetric})

// AddMetric the usage of the command immediately
if rootFlags.TelemetryDebugMode {
if err != nil {
log.Error("Could not send telemetry data", zap.Error(err))
} else {
log.Info("Telemetry data sent")
}
}
}

}()
}

return nil
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Expand Up @@ -11,7 +11,7 @@ require (
github.com/dgraph-io/ristretto v0.0.3
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/docker/go-units v0.5.0
github.com/evanw/esbuild v0.15.18
github.com/evanw/esbuild v0.16.10
github.com/fatih/color v1.13.0
github.com/fsnotify/fsnotify v1.5.4
github.com/gavv/httpexpect/v2 v2.3.0
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Expand Up @@ -109,8 +109,8 @@ github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.m
github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
github.com/evanphx/json-patch/v5 v5.1.0 h1:B0aXl1o/1cP8NbviYiBMkcHBtUjIJ1/Ccg6b+SwCLQg=
github.com/evanw/esbuild v0.15.18 h1:CM7eAoUjjNkZs1LH0p6fkwtADrbFr4JV2SlT1bUMjEo=
github.com/evanw/esbuild v0.15.18/go.mod h1:iINY06rn799hi48UqEnaQvVfZWe6W9bET78LbvN8VWk=
github.com/evanw/esbuild v0.16.10 h1:Wn4sao3reOG21sbrdhkaSnsLOBh60rhz96IMpOwWJrs=
github.com/evanw/esbuild v0.16.10/go.mod h1:iINY06rn799hi48UqEnaQvVfZWe6W9bET78LbvN8VWk=
github.com/fasthttp/websocket v1.4.3 h1:qjhRJ/rTy4KB8oBxljEC00SDt6HUY9jLRfM601SUdS4=
github.com/fasthttp/websocket v1.4.3/go.mod h1:5r4oKssgS7W6Zn6mPWap3NWzNPJNzUUh3baWTOhcYQk=
github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4=
Expand Down
22 changes: 5 additions & 17 deletions packages/sdk/README.md
Expand Up @@ -20,20 +20,8 @@ npx create-wundergraph-app <project-name> -E simple

# Exports

## Client

This is the base javascript implementation for all WunderGraph clients.

```ts
import { Client } from '@wundergraph/sdk/client';
```

## Internal

This is only intended for internal plugin development. No api compatibility guarantees.

> **Warning**: The api may change at any time.

```ts
import { visitJSONSchema } from '@wundergraph/sdk/internal';
```
- [@wundergraph/sdk/client](./client)
- [@wundergraph/sdk/internal](./internal)
- [@wundergraph/sdk/internal/logger](./logger)
- [@wundergraph/sdk/server](./server)
- [@wundergraph/sdk/testing](./testing)
19 changes: 13 additions & 6 deletions packages/sdk/package.json
Expand Up @@ -19,6 +19,10 @@
"types": "./dist/internal/index.d.ts",
"default": "./dist/internal/index.js"
},
"./server": {
"types": "./dist/server/index.d.ts",
"default": "./dist/server/index.js"
},
"./internal/logger": {
"types": "./dist/logger/index.d.ts",
"default": "./dist/logger/index.js"
Expand All @@ -39,6 +43,9 @@
"internal": [
"./dist/internal"
],
"server": [
"./dist/server"
],
"internal/logger": [
"./dist/logger"
]
Expand Down Expand Up @@ -109,22 +116,22 @@
"@web-std/fetch": "^4.1.0",
"@wundergraph/protobuf": "workspace:^0.100.0",
"@wundergraph/wunderctl": "workspace:>=0.121.0",
"axios": "^0.26.1",
"axios": "^0.27.2",
"axios-retry": "^3.3.1",
"close-with-grace": "^1.1.0",
"execa": "5.1.1",
"fastify": "^4.9.2",
"fastify-plugin": "^4.3.0",
"graphql": "^16.3.0",
"graphql-helix": "^1.12.0",
"fastify": "^4.10.2",
"fastify-plugin": "^4.4.0",
"graphql": "^16.6.0",
"graphql-helix": "^1.13.0",
"handlebars": "^4.7.7",
"js-yaml": "^4.1.0",
"json-schema": "^0.4.0",
"lodash": "^4.17.21",
"long": "^5.2.0",
"object-hash": "^2.2.0",
"openapi-types": "^10.0.0",
"pino": "^8.7.0",
"pino": "^8.8.0",
"pino-pretty": "^9.1.1",
"postman-collection": "^4.1.1",
"prettier": "^2.7.1",
Expand Down
4 changes: 1 addition & 3 deletions packages/sdk/src/client/README.md
@@ -1,8 +1,6 @@
# Wundergraph TypeScript Client

![wundergraph-client](https://img.shields.io/npm/v/@wundergraph/sdk.svg)

This is the base implementation of the WunderGraph HTTP protocol in TypeScript that can be used on both browser and server environments.
This directory contains the base implementation of the WunderGraph HTTP protocol in TypeScript that can be used on both browser and server environments.
It's used as the base interface for the Web client, React and Next.js implementations.

Use it to build your own 3rd party integration with WunderGraph.
Expand Down
@@ -1,7 +1,7 @@
//language=handlebars
export const template = `
import { {{ modelImports }} } from "./models"
import type { BaseRequestContext, WunderGraphRequest, WunderGraphResponse, AuthenticationResponse, AuthenticationHookRequest, HooksConfiguration, WsTransportOnConnectionInitResponse } from "@wundergraph/sdk";
import type { BaseRequestContext, WunderGraphRequest, WunderGraphResponse, AuthenticationResponse, AuthenticationHookRequest, HooksConfiguration, WsTransportOnConnectionInitResponse } from "@wundergraph/sdk/server";
import type { InternalClient } from "./wundergraph.internal.client"
import type { User } from "./wundergraph.server"

Expand Down
@@ -1,6 +1,6 @@
//language=handlebars
export const template = `
import type { OperationArgsWithInput, InternalClient as BaseClient } from "@wundergraph/sdk";
import type { OperationArgsWithInput, InternalClient as BaseClient } from "@wundergraph/sdk/server";
import { {{ modelImports }} } from "./models"

export interface Queries {
Expand Down
Expand Up @@ -2,7 +2,7 @@
export const template = `
import type { HooksConfig } from "./wundergraph.hooks";
import type { InternalClient } from "./wundergraph.internal.client"
import type { GraphQLServerConfig, BaseRequestContext, WunderGraphUser } from "@wundergraph/sdk";
import type { GraphQLServerConfig, BaseRequestContext, WunderGraphUser } from "@wundergraph/sdk/server";

export type Role = {{{ roleDefinitions }}};

Expand Down
@@ -1,6 +1,6 @@
//language=handlebars
export const template = `
import { WebhookConfiguration } from '@wundergraph/sdk';
import type { WebhookConfiguration } from '@wundergraph/sdk/server';

export type WebhooksConfig = {
{{#each webhooks}}
Expand Down
89 changes: 6 additions & 83 deletions packages/sdk/src/configure/index.ts
Expand Up @@ -9,7 +9,7 @@ import {
StaticApiCustom,
WG_DATA_SOURCE_POLLING_MODE,
} from '../definition';
import { mergeApis, removeBaseSchema } from '../definition/merge';
import { mergeApis } from '../definition/merge';
import { generateDotGraphQLConfig } from '../dotgraphqlconfig';
import { GraphQLOperation, loadOperations, parseOperations, removeHookVariables } from '../graphql/operations';
import { GenerateCode, Template } from '../codegen';
Expand Down Expand Up @@ -41,34 +41,25 @@ import {
parse,
parseType,
print,
stripIgnoredCharacters,
visit,
} from 'graphql';
import { PostmanBuilder } from '../postman/builder';
import path from 'path';
import { applyNamespaceToApi } from '../definition/namespacing';
import _ from 'lodash';
import { wunderctlExec } from '../wunderctlexec';
import { CustomizeMutation, CustomizeQuery, CustomizeSubscription, OperationsConfiguration } from './operations';
import {
AuthenticationHookRequest,
AuthenticationResponse,
ResolvedServerOptions,
WunderGraphHooksAndServerConfig,
WunderGraphUser,
} from '../middleware/types';
} from '../server/types';
import { getWebhooks } from '../webhooks';
import process from 'node:process';
import {
NodeOptions,
ResolvedNodeOptions,
ResolvedServerOptions,
resolveNodeOptions,
resolveServerOptions,
serverOptionsWithDefaults,
} from './options';
import { NodeOptions, ResolvedNodeOptions, resolveNodeOptions } from './options';
import { EnvironmentVariable, InputVariable, mapInputVariable, resolveConfigurationVariable } from './variables';
import { InternalClient } from '../middleware/internal-client';
import { Logger } from '../logger';
import { resolveServerOptions, serverOptionsWithDefaults } from '../server/util';

export interface WunderGraphCorsConfiguration {
allowedOrigins: InputVariable[];
Expand Down Expand Up @@ -144,68 +135,6 @@ export interface DotGraphQLConfig {
hasDotWunderGraphDirectory?: boolean;
}

export enum HooksConfigurationOperationType {
Queries = 'queries',
Mutations = 'mutations',
Subscriptions = 'subscriptions',
}

export interface OperationHookFunction {
(...args: any[]): Promise<any>;
}

export interface OperationHooksConfiguration<AsyncFn = OperationHookFunction> {
mockResolve?: AsyncFn;
preResolve?: AsyncFn;
postResolve?: AsyncFn;
mutatingPreResolve?: AsyncFn;
mutatingPostResolve?: AsyncFn;
customResolve?: AsyncFn;
}

// Any is used here because the exact type of the hooks is not known at compile time
// We could work with an index signature + base type, but that would allow to add arbitrary data to the hooks
export type OperationHooks = Record<string, any>;

export interface HooksConfiguration<
Queries extends OperationHooks = OperationHooks,
Mutations extends OperationHooks = OperationHooks,
Subscriptions extends OperationHooks = OperationHooks,
User extends WunderGraphUser = WunderGraphUser,
// Any is used here because the exact type of the base client is not known at compile time
// We could work with an index signature + base type, but that would allow to add arbitrary data to the client
IC extends InternalClient = InternalClient<any, any>
> {
global?: {
httpTransport?: {
onOriginRequest?: {
hook: OperationHookFunction;
enableForOperations?: string[];
enableForAllOperations?: boolean;
};
onOriginResponse?: {
hook: OperationHookFunction;
enableForOperations?: string[];
enableForAllOperations?: boolean;
};
};
wsTransport?: {
onConnectionInit?: {
hook: OperationHookFunction;
enableForDataSources: string[];
};
};
};
authentication?: {
postAuthentication?: (hook: AuthenticationHookRequest<User, IC>) => Promise<void>;
mutatingPostAuthentication?: (hook: AuthenticationHookRequest<User, IC>) => Promise<AuthenticationResponse<User>>;
revalidate?: (hook: AuthenticationHookRequest<User, IC>) => Promise<AuthenticationResponse<User>>;
postLogout?: (hook: AuthenticationHookRequest<User, IC>) => Promise<void>;
};
[HooksConfigurationOperationType.Queries]?: Queries;
[HooksConfigurationOperationType.Mutations]?: Mutations;
[HooksConfigurationOperationType.Subscriptions]?: Subscriptions;
}
export interface DeploymentAPI {
apiConfig: () => {
id: string;
Expand Down Expand Up @@ -323,13 +252,11 @@ const resolveConfig = async (config: WunderGraphConfigApplicationConfig): Promis
};

const graphqlApis = config.server?.graphqlServers?.map((gs) => {
const serverPath = customGqlServerMountPath(gs.serverName);

return introspectGraphqlServer({
skipRenameRootFields: gs.skipRenameRootFields,
url: '',
baseUrl: serverOptions.serverUrl,
path: serverPath,
path: gs.routeUrl,
apiNamespace: gs.apiNamespace,
schema: gs.schema,
});
Expand Down Expand Up @@ -1093,10 +1020,6 @@ const mapDataSource = (source: DataSource): DataSourceConfiguration => {
return out;
};

export const customGqlServerMountPath = (name: string): string => {
return `/gqls/${name}/graphql`;
};

const trimTrailingSlash = (url: string): string => {
return url.endsWith('/') ? url.slice(0, -1) : url;
};