@contember/engine-http 1.2.0-alpha.15 → 1.2.0-alpha.16
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/dist/src/ProjectContainer.d.ts +3 -2
- package/dist/src/ProjectContainer.d.ts.map +1 -1
- package/dist/src/ProjectGroupContainer.d.ts +2 -0
- package/dist/src/ProjectGroupContainer.d.ts.map +1 -1
- package/dist/src/common/ErrorMiddleware.d.ts +2 -1
- package/dist/src/common/ErrorMiddleware.d.ts.map +1 -1
- package/dist/src/common/ErrorMiddleware.js +1 -2
- package/dist/src/common/ErrorMiddleware.js.map +1 -1
- package/dist/src/common/LoggerMiddleware.d.ts +8 -0
- package/dist/src/common/LoggerMiddleware.d.ts.map +1 -0
- package/dist/src/common/LoggerMiddleware.js +32 -0
- package/dist/src/common/LoggerMiddleware.js.map +1 -0
- package/dist/src/common/TimerMiddleware.d.ts +2 -1
- package/dist/src/common/TimerMiddleware.d.ts.map +1 -1
- package/dist/src/common/TimerMiddleware.js +6 -5
- package/dist/src/common/TimerMiddleware.js.map +1 -1
- package/dist/src/common/index.d.ts +1 -0
- package/dist/src/common/index.d.ts.map +1 -1
- package/dist/src/common/index.js +1 -0
- package/dist/src/common/index.js.map +1 -1
- package/dist/src/config.d.ts +4 -1
- package/dist/src/config.d.ts.map +1 -1
- package/dist/src/content/ContentApiMiddlewareFactory.d.ts +2 -2
- package/dist/src/content/ContentApiMiddlewareFactory.d.ts.map +1 -1
- package/dist/src/content/ContentApiMiddlewareFactory.js +30 -22
- package/dist/src/content/ContentApiMiddlewareFactory.js.map +1 -1
- package/dist/src/content/ContentQueryHandlerFactory.d.ts +3 -4
- package/dist/src/content/ContentQueryHandlerFactory.d.ts.map +1 -1
- package/dist/src/content/ContentQueryHandlerFactory.js +2 -12
- package/dist/src/content/ContentQueryHandlerFactory.js.map +1 -1
- package/dist/src/content/ContentSchemaResolver.d.ts +3 -2
- package/dist/src/content/ContentSchemaResolver.d.ts.map +1 -1
- package/dist/src/content/ContentSchemaResolver.js +13 -8
- package/dist/src/content/ContentSchemaResolver.js.map +1 -1
- package/dist/src/graphql/execution.d.ts +5 -2
- package/dist/src/graphql/execution.d.ts.map +1 -1
- package/dist/src/graphql/execution.js +73 -20
- package/dist/src/graphql/execution.js.map +1 -1
- package/dist/src/graphql/index.d.ts +0 -1
- package/dist/src/graphql/index.d.ts.map +1 -1
- package/dist/src/graphql/index.js +0 -1
- package/dist/src/graphql/index.js.map +1 -1
- package/dist/src/graphql/state.d.ts.map +1 -1
- package/dist/src/graphql/state.js +2 -10
- package/dist/src/graphql/state.js.map +1 -1
- package/dist/src/system/SystemApiMiddlewareFactory.d.ts +2 -2
- package/dist/src/system/SystemApiMiddlewareFactory.d.ts.map +1 -1
- package/dist/src/system/SystemApiMiddlewareFactory.js +28 -25
- package/dist/src/system/SystemApiMiddlewareFactory.js.map +1 -1
- package/dist/src/system/SystemGraphQLContextFactory.d.ts.map +1 -1
- package/dist/src/system/SystemGraphQLContextFactory.js +3 -1
- package/dist/src/system/SystemGraphQLContextFactory.js.map +1 -1
- package/dist/src/system/SystemGraphQLHandlerFactory.d.ts +2 -3
- package/dist/src/system/SystemGraphQLHandlerFactory.d.ts.map +1 -1
- package/dist/src/system/SystemGraphQLHandlerFactory.js +1 -11
- package/dist/src/system/SystemGraphQLHandlerFactory.js.map +1 -1
- package/dist/src/tenant/TenantApiMiddlewareFactory.d.ts +2 -2
- package/dist/src/tenant/TenantApiMiddlewareFactory.d.ts.map +1 -1
- package/dist/src/tenant/TenantApiMiddlewareFactory.js +16 -5
- package/dist/src/tenant/TenantApiMiddlewareFactory.js.map +1 -1
- package/dist/src/tenant/TenantGraphQLContextFactory.d.ts +3 -1
- package/dist/src/tenant/TenantGraphQLContextFactory.d.ts.map +1 -1
- package/dist/src/tenant/TenantGraphQLContextFactory.js +2 -2
- package/dist/src/tenant/TenantGraphQLContextFactory.js.map +1 -1
- package/dist/src/tenant/TenantGraphQLHandlerFactory.d.ts +2 -3
- package/dist/src/tenant/TenantGraphQLHandlerFactory.d.ts.map +1 -1
- package/dist/src/tenant/TenantGraphQLHandlerFactory.js +1 -12
- package/dist/src/tenant/TenantGraphQLHandlerFactory.js.map +1 -1
- package/dist/src/transfer/ExportApiMiddlewareFactory.d.ts.map +1 -1
- package/dist/src/transfer/ExportApiMiddlewareFactory.js +1 -4
- package/dist/src/transfer/ExportApiMiddlewareFactory.js.map +1 -1
- package/dist/src/transfer/ImportExecutor.d.ts +1 -3
- package/dist/src/transfer/ImportExecutor.d.ts.map +1 -1
- package/dist/src/transfer/ImportExecutor.js +2 -3
- package/dist/src/transfer/ImportExecutor.js.map +1 -1
- package/dist/src/tsconfig.tsbuildinfo +1 -1
- package/dist/tests/tsconfig.tsbuildinfo +1 -1
- package/package.json +10 -10
- package/src/ProjectContainer.ts +4 -2
- package/src/ProjectGroupContainer.ts +2 -0
- package/src/common/ErrorMiddleware.ts +3 -3
- package/src/common/LoggerMiddleware.ts +33 -0
- package/src/common/TimerMiddleware.ts +10 -10
- package/src/common/index.ts +1 -0
- package/src/config.ts +6 -1
- package/src/content/ContentApiMiddlewareFactory.ts +38 -25
- package/src/content/ContentQueryHandlerFactory.ts +4 -17
- package/src/content/ContentSchemaResolver.ts +16 -11
- package/src/graphql/execution.ts +88 -22
- package/src/graphql/index.ts +0 -1
- package/src/graphql/state.ts +2 -12
- package/src/system/SystemApiMiddlewareFactory.ts +36 -27
- package/src/system/SystemGraphQLContextFactory.ts +4 -1
- package/src/system/SystemGraphQLHandlerFactory.ts +0 -12
- package/src/tenant/TenantApiMiddlewareFactory.ts +21 -6
- package/src/tenant/TenantGraphQLContextFactory.ts +4 -1
- package/src/tenant/TenantGraphQLHandlerFactory.ts +0 -12
- package/src/transfer/ExportApiMiddlewareFactory.ts +1 -4
- package/src/transfer/ImportExecutor.ts +1 -3
- package/src/tsconfig.json +12 -9
- package/dist/src/graphql/errors.d.ts +0 -13
- package/dist/src/graphql/errors.d.ts.map +0 -1
- package/dist/src/graphql/errors.js +0 -38
- package/dist/src/graphql/errors.js.map +0 -1
- package/src/graphql/errors.ts +0 -49
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@contember/engine-http",
|
|
3
|
-
"version": "1.2.0-alpha.
|
|
3
|
+
"version": "1.2.0-alpha.16",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"main": "dist/src/index.js",
|
|
6
6
|
"typings": "dist/src/index.d.ts",
|
|
@@ -9,15 +9,15 @@
|
|
|
9
9
|
},
|
|
10
10
|
"dependencies": {
|
|
11
11
|
"@apollographql/graphql-playground-html": "^1.6.24",
|
|
12
|
-
"@contember/database": "^1.2.0-alpha.
|
|
13
|
-
"@contember/engine-content-api": "^1.2.0-alpha.
|
|
14
|
-
"@contember/engine-plugins": "^1.2.0-alpha.
|
|
15
|
-
"@contember/engine-system-api": "^1.2.0-alpha.
|
|
16
|
-
"@contember/engine-tenant-api": "^1.2.0-alpha.
|
|
17
|
-
"@contember/graphql-utils": "^1.2.0-alpha.
|
|
18
|
-
"@contember/schema": "^1.2.0-alpha.
|
|
19
|
-
"@contember/schema-utils": "^1.2.0-alpha.
|
|
20
|
-
"@contember/typesafe": "^1.2.0-alpha.
|
|
12
|
+
"@contember/database": "^1.2.0-alpha.16",
|
|
13
|
+
"@contember/engine-content-api": "^1.2.0-alpha.16",
|
|
14
|
+
"@contember/engine-plugins": "^1.2.0-alpha.16",
|
|
15
|
+
"@contember/engine-system-api": "^1.2.0-alpha.16",
|
|
16
|
+
"@contember/engine-tenant-api": "^1.2.0-alpha.16",
|
|
17
|
+
"@contember/graphql-utils": "^1.2.0-alpha.16",
|
|
18
|
+
"@contember/schema": "^1.2.0-alpha.16",
|
|
19
|
+
"@contember/schema-utils": "^1.2.0-alpha.16",
|
|
20
|
+
"@contember/typesafe": "^1.2.0-alpha.16",
|
|
21
21
|
"@graphql-tools/schema": "^8.3.5",
|
|
22
22
|
"@types/lru-cache": "^7.10.10",
|
|
23
23
|
"accepts": "^1.3.7",
|
package/src/ProjectContainer.ts
CHANGED
|
@@ -2,12 +2,14 @@ import { DatabaseContextFactory } from '@contember/engine-system-api'
|
|
|
2
2
|
import { Connection } from '@contember/database'
|
|
3
3
|
import { ProjectConfig } from './config'
|
|
4
4
|
import { ContentSchemaResolver, GraphQlSchemaFactory } from './content'
|
|
5
|
-
import { Logger } from '@contember/
|
|
5
|
+
import { Logger } from '@contember/logger'
|
|
6
6
|
|
|
7
7
|
export interface ProjectContainer {
|
|
8
8
|
systemDatabaseContextFactory: DatabaseContextFactory
|
|
9
9
|
project: ProjectConfig
|
|
10
|
+
logger: Logger
|
|
10
11
|
connection: Connection
|
|
12
|
+
readConnection: Connection
|
|
11
13
|
graphQlSchemaFactory: GraphQlSchemaFactory
|
|
12
14
|
contentSchemaResolver: ContentSchemaResolver
|
|
13
15
|
}
|
|
@@ -15,6 +17,6 @@ export interface ProjectContainer {
|
|
|
15
17
|
export interface ProjectContainerResolver {
|
|
16
18
|
onCreate: ((container: ProjectContainer) => void | (() => void))[]
|
|
17
19
|
|
|
18
|
-
getProjectContainer(slug: string, options?: { alias?: boolean
|
|
20
|
+
getProjectContainer(slug: string, options?: { alias?: boolean }): Promise<ProjectContainer | undefined>
|
|
19
21
|
}
|
|
20
22
|
|
|
@@ -10,10 +10,12 @@ import { Authenticator } from './common'
|
|
|
10
10
|
import { TenantGraphQLHandler } from './tenant'
|
|
11
11
|
import { SystemGraphQLHandler } from './system'
|
|
12
12
|
import { ProjectMembershipResolver } from './content'
|
|
13
|
+
import { Logger } from '@contember/logger'
|
|
13
14
|
|
|
14
15
|
export interface ProjectGroupContainer {
|
|
15
16
|
slug: string | undefined
|
|
16
17
|
|
|
18
|
+
logger: Logger
|
|
17
19
|
authenticator: Authenticator
|
|
18
20
|
projectMembershipResolver: ProjectMembershipResolver
|
|
19
21
|
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { KoaMiddleware } from '../koa'
|
|
2
2
|
import { HttpError } from './HttpError'
|
|
3
3
|
import { AuthResult } from './Authorizator'
|
|
4
|
+
import { LoggerMiddlewareState } from './LoggerMiddleware'
|
|
4
5
|
|
|
5
6
|
export class ErrorMiddlewareFactory {
|
|
6
7
|
constructor(
|
|
@@ -8,7 +9,7 @@ export class ErrorMiddlewareFactory {
|
|
|
8
9
|
) {
|
|
9
10
|
}
|
|
10
11
|
|
|
11
|
-
public create(): KoaMiddleware<{ authResult?: AuthResult }> {
|
|
12
|
+
public create(): KoaMiddleware<{ authResult?: AuthResult } & LoggerMiddlewareState> {
|
|
12
13
|
return async (ctx, next) => {
|
|
13
14
|
try {
|
|
14
15
|
await next()
|
|
@@ -26,8 +27,7 @@ export class ErrorMiddlewareFactory {
|
|
|
26
27
|
} else {
|
|
27
28
|
ctx.status = 500
|
|
28
29
|
ctx.body = JSON.stringify({ errors: [{ message: 'Internal server error' }] })
|
|
29
|
-
|
|
30
|
-
console.error(e)
|
|
30
|
+
ctx.state.logger.error(e)
|
|
31
31
|
}
|
|
32
32
|
}
|
|
33
33
|
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { KoaMiddleware } from '../koa'
|
|
2
|
+
import { FingerCrossedLoggerHandler, Logger } from '@contember/logger'
|
|
3
|
+
|
|
4
|
+
export interface LoggerMiddlewareState {
|
|
5
|
+
logger: Logger
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export const LoggerRequestSymbol = Symbol()
|
|
9
|
+
|
|
10
|
+
export const createLoggerMiddleware = (logger: Logger) => {
|
|
11
|
+
const loggerMiddleware: KoaMiddleware<LoggerMiddlewareState> = async (ctx, next) => {
|
|
12
|
+
return await logger.scope(async logger => {
|
|
13
|
+
ctx.state.logger = logger
|
|
14
|
+
logger.debug('Request processing started', {
|
|
15
|
+
body: ctx.request.body,
|
|
16
|
+
query: ctx.request.query,
|
|
17
|
+
})
|
|
18
|
+
try {
|
|
19
|
+
return await next()
|
|
20
|
+
} finally {
|
|
21
|
+
logger.debug('Request processing finished')
|
|
22
|
+
}
|
|
23
|
+
}, {
|
|
24
|
+
method: ctx.request.method,
|
|
25
|
+
uri: ctx.request.originalUrl,
|
|
26
|
+
requestId: Math.random().toString().substring(2),
|
|
27
|
+
[LoggerRequestSymbol]: ctx.request,
|
|
28
|
+
}, {
|
|
29
|
+
handler: FingerCrossedLoggerHandler.factory(),
|
|
30
|
+
})
|
|
31
|
+
}
|
|
32
|
+
return loggerMiddleware
|
|
33
|
+
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { KoaMiddleware } from '../koa'
|
|
2
2
|
import { Readable } from 'stream'
|
|
3
|
+
import { LoggerMiddlewareState } from './LoggerMiddleware'
|
|
3
4
|
|
|
4
5
|
type EventTime = { label: string; start: number; duration?: number }
|
|
5
6
|
|
|
@@ -10,8 +11,8 @@ export interface TimerMiddlewareState {
|
|
|
10
11
|
sendServerTimingHeader: boolean
|
|
11
12
|
}
|
|
12
13
|
|
|
13
|
-
export const createTimerMiddleware = ({ debugMode }: { debugMode: boolean }): KoaMiddleware<TimerMiddlewareState> => {
|
|
14
|
-
const timer: KoaMiddleware<TimerMiddlewareState> = async (ctx, next) => {
|
|
14
|
+
export const createTimerMiddleware = ({ debugMode }: { debugMode: boolean }): KoaMiddleware<TimerMiddlewareState & LoggerMiddlewareState> => {
|
|
15
|
+
const timer: KoaMiddleware<TimerMiddlewareState & LoggerMiddlewareState> = async (ctx, next) => {
|
|
15
16
|
const times: EventTime[] = []
|
|
16
17
|
const globalStart = new Date().getTime()
|
|
17
18
|
ctx.state.timer = async (name: string, cb) => {
|
|
@@ -34,17 +35,16 @@ export const createTimerMiddleware = ({ debugMode }: { debugMode: boolean }): Ko
|
|
|
34
35
|
ctx.response.set('server-timing', times.map(it => `${it.label};desc="${it.label} T+${it.start}";dur=${it.duration ?? -1}`).join(', '))
|
|
35
36
|
}
|
|
36
37
|
|
|
37
|
-
const emit = () => {
|
|
38
|
-
const eventsDescription = times
|
|
39
|
-
.map(it => `${it.label} T+${it.start}ms ${it.duration !== undefined ? it.duration : '[unknown]'}ms`)
|
|
40
|
-
.join('; ')
|
|
41
38
|
|
|
39
|
+
const emit = () => {
|
|
42
40
|
const total = new Date().getTime() - globalStart
|
|
43
41
|
const timeLabel = total > 500 ? 'TIME_SLOW' : 'TIME_OK'
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
42
|
+
ctx.state.logger.info(ctx.response.status < 400 ? `Request successful` : 'Request failed', {
|
|
43
|
+
status: ctx.response.status,
|
|
44
|
+
timeLabel: timeLabel,
|
|
45
|
+
totalTimeMs: total,
|
|
46
|
+
events: times,
|
|
47
|
+
})
|
|
48
48
|
}
|
|
49
49
|
|
|
50
50
|
if (ctx.response.body instanceof Readable) {
|
package/src/common/index.ts
CHANGED
package/src/config.ts
CHANGED
|
@@ -8,8 +8,13 @@ export type ProjectConfig = {
|
|
|
8
8
|
readonly db:
|
|
9
9
|
& DatabaseConfig
|
|
10
10
|
& {
|
|
11
|
-
pool?: PoolConfig
|
|
11
|
+
pool?: Omit<PoolConfig, 'logError'>
|
|
12
12
|
systemSchema?: string
|
|
13
|
+
read?:
|
|
14
|
+
& Partial<DatabaseConfig>
|
|
15
|
+
& {
|
|
16
|
+
pool?: Omit<PoolConfig, 'logError'>
|
|
17
|
+
}
|
|
13
18
|
}
|
|
14
19
|
} & Record<string, unknown>
|
|
15
20
|
|
|
@@ -1,20 +1,22 @@
|
|
|
1
1
|
import { KoaMiddleware, KoaRequestState } from '../koa'
|
|
2
2
|
import { ProjectGroupResolver, ProjectInfoMiddlewareState } from '../project-common'
|
|
3
|
-
import { AuthResult, HttpError, TimerMiddlewareState } from '../common'
|
|
3
|
+
import { AuthResult, HttpError, LoggerMiddlewareState, TimerMiddlewareState } from '../common'
|
|
4
4
|
import { StageBySlugQuery } from '@contember/engine-system-api'
|
|
5
5
|
import { NotModifiedChecker } from './NotModifiedChecker'
|
|
6
6
|
import { ContentGraphQLContextFactory } from './ContentGraphQLContextFactory'
|
|
7
7
|
import { ContentQueryHandler, ContentQueryHandlerFactory } from './ContentQueryHandlerFactory'
|
|
8
8
|
import { GraphQLSchema } from 'graphql'
|
|
9
9
|
import { GraphQLKoaState } from '../graphql'
|
|
10
|
-
import { Logger } from '@contember/engine-common'
|
|
11
10
|
|
|
12
11
|
type ContentApiMiddlewareKoaState =
|
|
13
12
|
& TimerMiddlewareState
|
|
14
13
|
& KoaRequestState
|
|
15
14
|
& GraphQLKoaState
|
|
16
15
|
& ProjectInfoMiddlewareState
|
|
17
|
-
&
|
|
16
|
+
& LoggerMiddlewareState
|
|
17
|
+
& {
|
|
18
|
+
authResult: AuthResult
|
|
19
|
+
}
|
|
18
20
|
|
|
19
21
|
|
|
20
22
|
const debugHeader = 'x-contember-debug'
|
|
@@ -37,20 +39,24 @@ export class ContentApiMiddlewareFactory {
|
|
|
37
39
|
koaContext.state.projectGroup = groupContainer.slug
|
|
38
40
|
|
|
39
41
|
const authResult = await groupContainer.authenticator.authenticate({ request, timer })
|
|
42
|
+
koaContext.state.logger.debug('User authenticated', { authResult })
|
|
40
43
|
koaContext.state.authResult = authResult
|
|
41
44
|
|
|
42
|
-
// eslint-disable-next-line no-console
|
|
43
|
-
const logger = new Logger(console.log)
|
|
44
|
-
logger.group(`Initializing ${groupContainer.slug}/${params.projectSlug}`)
|
|
45
45
|
|
|
46
46
|
const projectContainer = await groupContainer.projectContainerResolver.getProjectContainer(params.projectSlug, {
|
|
47
47
|
alias: true,
|
|
48
|
-
logger,
|
|
49
48
|
})
|
|
50
|
-
|
|
49
|
+
|
|
51
50
|
if (projectContainer === undefined) {
|
|
52
51
|
throw new HttpError(`Project ${params.projectSlug} NOT found`, 404)
|
|
53
52
|
}
|
|
53
|
+
const requestLogger = koaContext.state.logger.child({
|
|
54
|
+
...projectContainer.logger.attributes,
|
|
55
|
+
module: 'content',
|
|
56
|
+
user: authResult.identityId,
|
|
57
|
+
})
|
|
58
|
+
koaContext.state.logger = requestLogger
|
|
59
|
+
|
|
54
60
|
const project = projectContainer.project
|
|
55
61
|
koaContext.state.project = project.slug
|
|
56
62
|
|
|
@@ -85,6 +91,7 @@ export class ContentApiMiddlewareFactory {
|
|
|
85
91
|
},
|
|
86
92
|
}),
|
|
87
93
|
)
|
|
94
|
+
requestLogger.debug('Memberships fetched', { memberships })
|
|
88
95
|
|
|
89
96
|
const debugHeaderValue = request.get(debugHeader).trim()
|
|
90
97
|
const requestDebug = debugHeaderValue === '1' && fetchedMemberships.some(it => schema.acl.roles[it.role]?.debug)
|
|
@@ -94,7 +101,6 @@ export class ContentApiMiddlewareFactory {
|
|
|
94
101
|
|
|
95
102
|
const projectRoles = memberships.map(it => it.role)
|
|
96
103
|
|
|
97
|
-
const contentDatabase = projectContainer.connection.createClient(stage.schema, { module: 'content' })
|
|
98
104
|
|
|
99
105
|
const [graphQlSchema, permissions] = await timer('GraphQLSchemaCreate', () => projectContainer.graphQlSchemaFactory.create(schema, {
|
|
100
106
|
projectRoles: projectRoles,
|
|
@@ -105,29 +111,36 @@ export class ContentApiMiddlewareFactory {
|
|
|
105
111
|
if (existingHandler) {
|
|
106
112
|
return existingHandler
|
|
107
113
|
}
|
|
108
|
-
const newHandler = await this.handlerFactory.create(graphQlSchema
|
|
114
|
+
const newHandler = await this.handlerFactory.create(graphQlSchema)
|
|
109
115
|
handlerCache.set(graphQlSchema, newHandler)
|
|
110
116
|
return newHandler
|
|
111
117
|
})()
|
|
112
118
|
|
|
119
|
+
await requestLogger.scope(async logger => {
|
|
120
|
+
logger.debug('Content query processing started')
|
|
113
121
|
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
122
|
+
await timer('GraphQL', () => handler({
|
|
123
|
+
request,
|
|
124
|
+
response,
|
|
125
|
+
createContext: ({ operation }) => {
|
|
126
|
+
const connection = operation === 'query' ? projectContainer.readConnection : projectContainer.connection
|
|
127
|
+
const contentDatabase = connection.createClient(stage.schema, { module: 'content' })
|
|
128
|
+
|
|
129
|
+
return this.contentGraphqlContextFactory.create({
|
|
130
|
+
db: contentDatabase,
|
|
131
|
+
authResult,
|
|
132
|
+
memberships,
|
|
133
|
+
permissions,
|
|
134
|
+
schema,
|
|
135
|
+
timer,
|
|
136
|
+
koaContext,
|
|
137
|
+
requestDebug,
|
|
138
|
+
})
|
|
139
|
+
},
|
|
140
|
+
}))
|
|
141
|
+
logger.debug('Content query finished')
|
|
123
142
|
})
|
|
124
143
|
|
|
125
|
-
await timer('GraphQL', () => handler({
|
|
126
|
-
request,
|
|
127
|
-
response,
|
|
128
|
-
context: graphqlContext,
|
|
129
|
-
}))
|
|
130
|
-
|
|
131
144
|
|
|
132
145
|
notModifiedRes?.setResponseHeader(response)
|
|
133
146
|
}
|
|
@@ -1,33 +1,20 @@
|
|
|
1
1
|
import { GraphQLSchema } from 'graphql'
|
|
2
2
|
import {
|
|
3
3
|
createDbQueriesListener,
|
|
4
|
-
createErrorListener,
|
|
5
4
|
createGraphQLQueryHandler,
|
|
6
5
|
createGraphqlRequestInfoProviderListener,
|
|
7
|
-
|
|
8
|
-
|
|
6
|
+
GraphQLListener,
|
|
7
|
+
GraphQLQueryHandler,
|
|
9
8
|
} from '../graphql'
|
|
10
9
|
import { ExtendedGraphqlContext } from './ContentGraphQLContextFactory'
|
|
11
10
|
|
|
12
11
|
export type ContentQueryHandler = GraphQLQueryHandler<ExtendedGraphqlContext>
|
|
13
12
|
|
|
14
13
|
export class ContentQueryHandlerFactory {
|
|
15
|
-
constructor(
|
|
16
|
-
private readonly debug: boolean,
|
|
17
|
-
private readonly errorLogger: ErrorLogger,
|
|
18
|
-
) {}
|
|
14
|
+
constructor(private readonly debug: boolean) {}
|
|
19
15
|
|
|
20
|
-
public create(graphQlSchema: GraphQLSchema
|
|
16
|
+
public create(graphQlSchema: GraphQLSchema): ContentQueryHandler {
|
|
21
17
|
const listeners: GraphQLListener<ExtendedGraphqlContext>[] = [
|
|
22
|
-
createErrorListener((err, ctx) => {
|
|
23
|
-
this.errorLogger(err, {
|
|
24
|
-
body: ctx.koaContext.request.body as string,
|
|
25
|
-
url: ctx.koaContext.request.originalUrl,
|
|
26
|
-
user: ctx.identityId,
|
|
27
|
-
module: 'content',
|
|
28
|
-
project: projectSlug,
|
|
29
|
-
})
|
|
30
|
-
}),
|
|
31
18
|
createGraphqlRequestInfoProviderListener(),
|
|
32
19
|
]
|
|
33
20
|
listeners.push(createDbQueriesListener(context => context.db, this.debug))
|
|
@@ -1,23 +1,28 @@
|
|
|
1
1
|
import { DatabaseContext, SchemaVersionBuilder, VersionedSchema } from '@contember/engine-system-api'
|
|
2
|
-
import { Schema } from '@contember/schema'
|
|
3
2
|
import { filterSchemaByStage } from '@contember/schema-utils'
|
|
4
3
|
|
|
4
|
+
|
|
5
5
|
export class ContentSchemaResolver {
|
|
6
|
-
private
|
|
6
|
+
private baseSchemaCache: VersionedSchema | undefined
|
|
7
|
+
private stageSchemaCache: { [stage: string]: VersionedSchema } = {}
|
|
7
8
|
|
|
8
|
-
constructor(private readonly schemaVersionBuilder: SchemaVersionBuilder) {
|
|
9
|
+
constructor(private readonly schemaVersionBuilder: SchemaVersionBuilder) {
|
|
10
|
+
}
|
|
9
11
|
|
|
10
12
|
public clearCache() {
|
|
11
|
-
this.
|
|
13
|
+
this.baseSchemaCache = undefined
|
|
14
|
+
this.stageSchemaCache = {}
|
|
12
15
|
}
|
|
13
16
|
|
|
14
|
-
public async getSchema(db: DatabaseContext, stage
|
|
15
|
-
const
|
|
16
|
-
|
|
17
|
-
if (
|
|
18
|
-
|
|
17
|
+
public async getSchema(db: DatabaseContext, stage?: string): Promise<VersionedSchema> {
|
|
18
|
+
const prevBaseSchema = this.baseSchemaCache
|
|
19
|
+
this.baseSchemaCache = await this.schemaVersionBuilder.buildSchema(db, prevBaseSchema)
|
|
20
|
+
if (prevBaseSchema !== this.baseSchemaCache) {
|
|
21
|
+
this.stageSchemaCache = {}
|
|
22
|
+
}
|
|
23
|
+
if (!stage) {
|
|
24
|
+
return this.baseSchemaCache
|
|
19
25
|
}
|
|
20
|
-
this.
|
|
21
|
-
return newSchema
|
|
26
|
+
return this.stageSchemaCache[stage] ??= filterSchemaByStage(this.baseSchemaCache, stage)
|
|
22
27
|
}
|
|
23
28
|
}
|
package/src/graphql/execution.ts
CHANGED
|
@@ -1,13 +1,28 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
DocumentNode,
|
|
3
|
+
execute,
|
|
4
|
+
GraphQLError,
|
|
5
|
+
GraphQLSchema,
|
|
6
|
+
Kind,
|
|
7
|
+
OperationDefinitionNode,
|
|
8
|
+
OperationTypeNode,
|
|
9
|
+
parse,
|
|
10
|
+
validate,
|
|
11
|
+
validateSchema,
|
|
12
|
+
} from 'graphql'
|
|
2
13
|
import LRUCache from 'lru-cache'
|
|
3
14
|
import { createHash } from 'crypto'
|
|
4
15
|
import { Request, Response } from 'koa'
|
|
16
|
+
import { logger } from '@contember/logger'
|
|
17
|
+
import { ForbiddenError } from '@contember/graphql-utils'
|
|
18
|
+
import { UserError } from '@contember/engine-content-api'
|
|
5
19
|
|
|
6
20
|
export interface GraphQLListener<Context> {
|
|
7
21
|
onStart?: (ctx: {}) => Omit<GraphQLListener<Context>, 'onStart'> | void
|
|
8
22
|
onExecute?: (ctx: {
|
|
9
23
|
context: Context
|
|
10
24
|
document: DocumentNode
|
|
25
|
+
operation: OperationTypeNode
|
|
11
26
|
}) => Omit<GraphQLListener<Context>, 'onStart' | 'onExecute'> | void
|
|
12
27
|
onResponse?: (ctx: {
|
|
13
28
|
response: any
|
|
@@ -23,7 +38,7 @@ interface FactoryArgs<Context> {
|
|
|
23
38
|
listeners: GraphQLListener<Context>[]
|
|
24
39
|
}
|
|
25
40
|
|
|
26
|
-
export type GraphQLQueryHandler<Context> = (args: {request: Request; response: Response;
|
|
41
|
+
export type GraphQLQueryHandler<Context> = (args: { request: Request; response: Response; createContext: ({}: { operation: OperationTypeNode }) => Context }) => any
|
|
27
42
|
|
|
28
43
|
const hitCacheMaxAgeSeconds = 10 * 60
|
|
29
44
|
const documentCacheMaxAgeSeconds = hitCacheMaxAgeSeconds * 10
|
|
@@ -46,7 +61,7 @@ export const createGraphQLQueryHandler = <Context>({
|
|
|
46
61
|
})
|
|
47
62
|
let lastPrune = Date.now()
|
|
48
63
|
|
|
49
|
-
return async ({ request, response,
|
|
64
|
+
return async ({ request, response, createContext }) => {
|
|
50
65
|
|
|
51
66
|
const now = Date.now()
|
|
52
67
|
if ((now - lastPrune) > pruneIntervalSeconds * 1000) {
|
|
@@ -81,49 +96,100 @@ export const createGraphQLQueryHandler = <Context>({
|
|
|
81
96
|
const resolvedRequest = request.method === 'POST' ? (request.body as any) : request.query
|
|
82
97
|
if (!resolvedRequest.query) {
|
|
83
98
|
return respond(400, {
|
|
84
|
-
errors: { message: 'Missing request query' },
|
|
99
|
+
errors: [{ message: 'Missing request query' }],
|
|
85
100
|
})
|
|
86
101
|
}
|
|
87
102
|
const queryHash = createHash('md5').update(resolvedRequest.query).digest('hex')
|
|
88
103
|
let doc = documentCache.get(queryHash)
|
|
89
104
|
if (!doc) {
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
documentCache.set(queryHash, doc)
|
|
98
|
-
}
|
|
99
|
-
hitCache.set(queryHash, true)
|
|
100
|
-
} catch (e) {
|
|
101
|
-
if (e instanceof GraphQLError) {
|
|
102
|
-
return respond(400, { errors: [e] })
|
|
103
|
-
}
|
|
104
|
-
throw e
|
|
105
|
+
doc = parse(resolvedRequest.query)
|
|
106
|
+
const validationResult = validate(schema, doc)
|
|
107
|
+
if (validationResult.length) {
|
|
108
|
+
return respond(400, { errors: validationResult })
|
|
109
|
+
}
|
|
110
|
+
if (hitCache.get(queryHash)) {
|
|
111
|
+
documentCache.set(queryHash, doc)
|
|
105
112
|
}
|
|
113
|
+
hitCache.set(queryHash, true)
|
|
106
114
|
}
|
|
107
115
|
const document = doc
|
|
116
|
+
const operationName = resolvedRequest.operationName ?? null
|
|
117
|
+
const operation = resolveOperationType(document, operationName)
|
|
118
|
+
|
|
108
119
|
|
|
120
|
+
const context = createContext({ operation })
|
|
109
121
|
listenersQueue.forEach(it => {
|
|
110
|
-
it.onExecute && listenersQueue.push(it.onExecute({ context, document }) || {})
|
|
122
|
+
it.onExecute && listenersQueue.push(it.onExecute({ context, document, operation }) || {})
|
|
111
123
|
})
|
|
112
124
|
const response = await execute({
|
|
113
125
|
schema,
|
|
114
126
|
document,
|
|
127
|
+
operationName: operationName,
|
|
115
128
|
variableValues: resolvedRequest.variables,
|
|
116
129
|
contextValue: context,
|
|
117
130
|
})
|
|
118
131
|
listenersQueue.forEach(it => {
|
|
119
132
|
it.onResponse && listenersQueue.push(it.onResponse({ context, response }) || {})
|
|
120
133
|
})
|
|
121
|
-
|
|
134
|
+
if (response.errors && response.errors.length > 0) {
|
|
135
|
+
const [code, errors] = processErrors(response.errors)
|
|
136
|
+
respond(code && response.data === null ? code : 200, { ...response, errors })
|
|
137
|
+
} else {
|
|
138
|
+
respond(200, response)
|
|
139
|
+
}
|
|
122
140
|
} catch (e) {
|
|
123
141
|
if (e instanceof GraphQLError) {
|
|
124
|
-
return respond(400, { errors: [e] })
|
|
142
|
+
return respond(e instanceof ForbiddenError ? 403 : 400, { errors: [e] })
|
|
125
143
|
}
|
|
126
144
|
return respond(500, { errors: [{ message: 'Internal error' }] })
|
|
127
145
|
}
|
|
128
146
|
}
|
|
129
147
|
}
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
const extractOriginalError = (e: Error): Error => {
|
|
151
|
+
if (e instanceof GraphQLError && e.originalError) {
|
|
152
|
+
return extractOriginalError(e.originalError)
|
|
153
|
+
}
|
|
154
|
+
if ('errors' in e && Array.isArray((e as any).errors) && (e as any).errors.length === 1) {
|
|
155
|
+
return extractOriginalError((e as any).errors[0])
|
|
156
|
+
}
|
|
157
|
+
return e
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const processErrors = (errors: readonly any[]): [number | null, any[]] => {
|
|
161
|
+
const resultErrors = []
|
|
162
|
+
let has400 = false
|
|
163
|
+
let has403 = false
|
|
164
|
+
let has500 = false
|
|
165
|
+
for (const error of errors) {
|
|
166
|
+
const originalError = extractOriginalError(error)
|
|
167
|
+
if (originalError instanceof GraphQLError) {
|
|
168
|
+
resultErrors.push(error)
|
|
169
|
+
has400 = true
|
|
170
|
+
} else if (originalError instanceof ForbiddenError) {
|
|
171
|
+
resultErrors.push(error)
|
|
172
|
+
has403 = true
|
|
173
|
+
} else if (originalError instanceof UserError) {
|
|
174
|
+
resultErrors.push({ message: error.message, locations: error.locations, path: error.path })
|
|
175
|
+
has400 = true
|
|
176
|
+
} else {
|
|
177
|
+
logger.error(originalError || error)
|
|
178
|
+
resultErrors.push({ message: 'Internal server error', locations: undefined, path: undefined })
|
|
179
|
+
has500 = true
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
return [has500 ? 500 : has400 ? 400 : has403 ? 403 : null, resultErrors]
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
const resolveOperationType = (document: DocumentNode, operationName: string | null): OperationTypeNode => {
|
|
187
|
+
for (const definition of document.definitions) {
|
|
188
|
+
if (definition.kind === Kind.OPERATION_DEFINITION) {
|
|
189
|
+
if (operationName === null || definition.name?.value === operationName) {
|
|
190
|
+
return definition.operation
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
throw new GraphQLError('Must provide an operation.')
|
|
195
|
+
}
|
package/src/graphql/index.ts
CHANGED
package/src/graphql/state.ts
CHANGED
|
@@ -1,22 +1,12 @@
|
|
|
1
|
-
import { DocumentNode, OperationTypeNode } from 'graphql'
|
|
2
1
|
import { GraphQLListener } from './execution'
|
|
3
2
|
import { KoaContext } from '../koa'
|
|
4
3
|
|
|
5
|
-
const getOperationFromDocument = (document: DocumentNode): OperationTypeNode | undefined => {
|
|
6
|
-
for (const node of document.definitions) {
|
|
7
|
-
if (node.kind === 'OperationDefinition') {
|
|
8
|
-
return node.operation
|
|
9
|
-
}
|
|
10
|
-
}
|
|
11
|
-
return undefined
|
|
12
|
-
}
|
|
13
|
-
|
|
14
4
|
export const createGraphqlRequestInfoProviderListener = (): GraphQLListener<{
|
|
15
5
|
koaContext: KoaContext<GraphQLKoaState>
|
|
16
6
|
}> => ({
|
|
17
|
-
onExecute: ({ context,
|
|
7
|
+
onExecute: ({ context, operation }) => {
|
|
18
8
|
context.koaContext.state.graphql = {
|
|
19
|
-
operationName:
|
|
9
|
+
operationName: operation,
|
|
20
10
|
}
|
|
21
11
|
},
|
|
22
12
|
})
|