-
-
Notifications
You must be signed in to change notification settings - Fork 350
/
Copy pathverifier.ts
223 lines (193 loc) · 6.26 KB
/
verifier.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
/**
* Provider Verifier service
* @module ProviderVerifier
*/
import pact from "@pact-foundation/pact-node"
import { qToPromise } from "../common/utils"
import { VerifierOptions as PactNodeVerifierOptions } from "@pact-foundation/pact-node"
import serviceFactory from "@pact-foundation/pact-node"
import { omit, isEmpty } from "lodash"
import * as express from "express"
import * as http from "http"
import logger from "../common/logger"
import { LogLevel } from "./options"
import ConfigurationError from "../errors/configurationError"
const HttpProxy = require("http-proxy")
const bodyParser = require("body-parser")
export interface ProviderState {
states?: [string]
}
export interface StateHandler {
[name: string]: () => Promise<any>
}
// See https://stackoverflow.com/questions/43357734/typescript-recursive-type-with-indexer/43359686
// as to why we can't use an intersection type here
// TL;DR - PactNodeVerifierOptions has an index type which enforces all keys to match the index type
export interface VerifierOptions {
logLevel?: LogLevel
requestFilter?: express.RequestHandler
stateHandlers?: StateHandler
providerBaseUrl: string
provider?: string
pactUrls?: string[]
pactBrokerBaseUrl?: string
providerStatesSetupUrl?: string
pactBrokerUsername?: string
pactBrokerPassword?: string
consumerVersionTag?: string
customProviderHeaders?: string[]
publishVerificationResult?: boolean
providerVersion?: string
pactBrokerUrl?: string
tags?: string[]
timeout?: number
monkeypatch?: string
format?: "json" | "RspecJunitFormatter"
out?: string
validateSSL?: boolean
changeOrigin?: boolean
}
export class Verifier {
private address: string = "http://localhost"
private stateSetupPath: string = "/_pactSetup"
private config: VerifierOptions
private deprecatedFields: string[] = ["providerStatesSetupUrl"]
constructor(config?: VerifierOptions) {
if (config) {
this.setConfig(config)
}
}
/**
* Verify a HTTP Provider
*
* @param config
*/
public verifyProvider(config?: VerifierOptions): Promise<any> {
logger.info("Verifying provider")
// Backwards compatibility
if (config) {
logger.warn(
"Passing options to verifyProvider() wil be deprecated in future versions, please provide to Verifier constructor instead"
)
this.setConfig(config)
}
if (isEmpty(this.config)) {
return Promise.reject(
new ConfigurationError("No configuration provided to verifier")
)
}
// Start the verification CLI proxy server
const app = this.createProxy()
const server = this.startProxy(app)
// Run the verification once the proxy server is available
return this.waitForServerReady(server)
.then(this.runProviderVerification())
.then(result => {
server.close()
return result
})
.catch(e => {
server.close()
throw e
})
}
// Run the Verification CLI process
private runProviderVerification() {
return (server: http.Server) => {
const opts = {
...omit(this.config, "handlers"),
...{ providerBaseUrl: `${this.address}:${server.address().port}` },
...{
providerStatesSetupUrl: `${this.address}:${server.address().port}${
this.stateSetupPath
}`,
},
} as PactNodeVerifierOptions
return qToPromise<any>(pact.verifyPacts(opts))
}
}
// Listens for the server start event
// Converts event Emitter to a Promise
private waitForServerReady(server: http.Server): Promise<http.Server> {
return new Promise((resolve, reject) => {
server.on("listening", () => resolve(server))
server.on("error", () =>
reject(new Error("Unable to start verification proxy server"))
)
})
}
// Get the Proxy we'll pass to the CLI for verification
private startProxy(
app: (request: http.IncomingMessage, response: http.ServerResponse) => void
): http.Server {
return http.createServer(app).listen()
}
// Get the Express app that will run on the HTTP Proxy
private createProxy(): express.Express {
const app = express()
const proxy = new HttpProxy()
app.use(this.stateSetupPath, bodyParser.json())
app.use(this.stateSetupPath, bodyParser.urlencoded({ extended: true }))
// Allow for request filtering
if (this.config.requestFilter !== undefined) {
app.use(this.config.requestFilter)
}
// Setup provider state handler
app.post(this.stateSetupPath, this.createProxyStateHandler())
// Proxy server will respond to Verifier process
app.all("/*", (req, res) => {
logger.debug("Proxing", req.path)
proxy.web(req, res, {
changeOrigin: this.config.changeOrigin === true,
secure: this.config.validateSSL === true,
target: this.config.providerBaseUrl,
})
})
return app
}
private createProxyStateHandler() {
return (req: any, res: any) => {
const message: ProviderState = req.body
return this.setupStates(message)
.then(() => res.sendStatus(200))
.catch(e => res.status(500).send(e))
}
}
// Lookup the handler based on the description, or get the default handler
private setupStates(descriptor: ProviderState): Promise<any> {
const promises: Array<Promise<any>> = new Array()
if (descriptor.states) {
descriptor.states.forEach(state => {
const handler = this.config.stateHandlers
? this.config.stateHandlers[state]
: null
if (handler) {
promises.push(handler())
} else {
logger.warn(`No state handler found for "${state}", ignorning`)
}
})
}
return Promise.all(promises)
}
private setConfig(config: VerifierOptions) {
this.config = config
this.deprecatedFields.forEach(f => {
if ((this.config as any)[f]) {
logger.warn(
`${f} is deprecated, and will be removed in future versions`
)
}
})
if (this.config.validateSSL === undefined) {
this.config.validateSSL = true
}
if (this.config.changeOrigin === undefined) {
this.config.changeOrigin = false
}
if (this.config.logLevel && !isEmpty(this.config.logLevel)) {
serviceFactory.logLevel(this.config.logLevel)
logger.level(this.config.logLevel)
}
}
}