Skip to content

Commit 8daef4c

Browse files
committed
wip tests
1 parent 5b1c4c9 commit 8daef4c

File tree

5 files changed

+76
-76
lines changed

5 files changed

+76
-76
lines changed

src/__tests__/request-builder.spec.ts

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,8 @@
1-
// import { buildUrlHeaders } from '../utils'
2-
import * as utils from '../utils'
1+
import { Utils } from '../utils'
32

43
describe('request builder test', () => {
5-
beforeEach(() => {
6-
jest.spyOn(utils, 'getRuntimeIngressHost').mockImplementation(async (runtimeName: string, headers: Record<string, string>) => { return 'fjfjfj'})
7-
})
84
it('support CF_HOST', async () => {
9-
const { url, headers } = await utils.buildUrlHeaders({
5+
const { url, headers } = await Utils.buildUrlHeaders({
106
'CF_API_KEY': 'the-token',
117
'CF_HOST': 'https://g.codefresh.io',
128
'CF_IMAGE': 'testImage'
@@ -16,12 +12,14 @@ describe('request builder test', () => {
1612
})
1713

1814
it('support CF_RUNTIME_NAME', async () => {
19-
const { url, headers } = await utils.buildUrlHeaders({
15+
const ingressHost = 'https://my.codefresh.ingress'
16+
jest.spyOn(Utils, 'getRuntimeIngressHost').mockResolvedValue(ingressHost)
17+
const { url, headers } = await Utils.buildUrlHeaders({
2018
'CF_API_KEY': 'the-token',
2119
'CF_RUNTIME_NAME': 'runtime',
2220
'CF_IMAGE': 'testImage'
2321
})
24-
expect(url).toEqual('https://g.codefresh.io/app-proxy/api/image-report?CF_IMAGE=testImage')
22+
expect(url).toEqual(`${ingressHost}/app-proxy/api/image-report?CF_IMAGE=testImage`)
2523
expect(headers).toEqual({ 'authorization': 'the-token' })
2624
})
2725

src/errors.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
export const errors = {
2+
EventSourceError: class extends Error {
3+
constructor(message?: string, name?: string) {
4+
super(message)
5+
this.name = name || 'EventSourceError'
6+
}
7+
},
8+
ValidationError: class extends Error {
9+
constructor(message?: string, name?: string) {
10+
super(message)
11+
this.name = name || 'ValidationError'
12+
}
13+
}
14+
}

src/main.ts

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
import EventSource from 'eventsource'
22

33
import { validate } from './validate'
4-
import { tryParseJson, errors, buildUrlHeaders } from './utils'
4+
import { Utils } from './utils'
5+
import { errors } from './errors'
56
import { logger, workflowLogger } from './logger'
67

78
const { EventSourceError } = errors
89

10+
911
/**
1012
* Take (CF_ prefixed) Env variables and perform http/s request (SSE) to app-proxy for image-report with CF_ENRICHERS
1113
*/
@@ -15,7 +17,7 @@ async function main(argv, env): Promise<void> {
1517
logger.debug('running with verbose log')
1618
}
1719
const payload = validate(env)
18-
const { url, headers } = await buildUrlHeaders(payload)
20+
const { url, headers } = await Utils.buildUrlHeaders(payload)
1921
if (verbose) {
2022
logger.debug(`payload: ${JSON.stringify(payload, null, 2)}`)
2123
logger.debug(`sending request: ${url}, headers: ${JSON.stringify(headers)}`)
@@ -37,7 +39,7 @@ async function main(argv, env): Promise<void> {
3739
logger.warn(event.data)
3840
})
3941
eventSource.addEventListener('workflow-log', function (event) {
40-
const log = tryParseJson(event.data)
42+
const log = Utils.tryParseJson(event.data)
4143
if (typeof log === 'object' && log.content && log.podName) {
4244
workflowLogger.info({ pod: log.podName, message: log.content })
4345
} else {
@@ -47,7 +49,7 @@ async function main(argv, env): Promise<void> {
4749
eventSource.addEventListener('error', (errorEvent) => {
4850
eventSource.close()
4951

50-
const error = tryParseJson(errorEvent.data)
52+
const error = Utils.tryParseJson(errorEvent.data)
5153
let name
5254
let message
5355
if (typeof error === 'string') {

src/utils.ts

Lines changed: 49 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -1,74 +1,60 @@
1-
import * as utils from './utils'
21
import { GraphQLClient, gql } from 'graphql-request'
32
import { get } from 'lodash'
4-
export const tryParseJson = (str: string) => {
5-
try {
6-
return JSON.parse(str)
7-
} catch {
8-
return str
9-
}
10-
}
113

12-
13-
/**
14-
* Build image-report url and headers
15-
* @param payload
16-
*/
17-
export async function buildUrlHeaders(payload: Record<string, string | undefined>) {
18-
const esc = encodeURIComponent
19-
const headers = { 'authorization': payload['CF_API_KEY']! }
20-
const runtimeName = payload['CF_RUNTIME_NAME']
21-
let host
22-
if (!runtimeName) {
23-
host = payload['CF_HOST']
24-
delete payload['CF_HOST']
25-
}
26-
else {
27-
host = await getRuntimeIngressHost(runtimeName, headers)
28-
delete payload['CF_RUNTIME_NAME']
29-
}
30-
delete payload['CF_API_KEY']
31-
const qs = Object.entries(payload).map(kv => `${esc(kv[0])}=${esc(kv[1] || '')}`).join('&')
32-
const url = `${host}/app-proxy/api/image-report?${qs}`
33-
if (payload['CF_LOCAL']) {
34-
return { url: `${host}/api/image-report?${qs}`, headers }
4+
import { errors } from './errors'
5+
export class Utils {
6+
/**
7+
* Build image-report url and headers
8+
* @param payload
9+
*/
10+
static async buildUrlHeaders(payload: Record<string, string | undefined>): Promise<{ url: string, headers: { authorization: string } }> {
11+
const esc = encodeURIComponent
12+
const headers = { 'authorization': payload['CF_API_KEY']! }
13+
const runtimeName = payload['CF_RUNTIME_NAME']
14+
let host
15+
if (!runtimeName) {
16+
host = payload['CF_HOST']
17+
delete payload['CF_HOST']
18+
} else {
19+
host = await this.getRuntimeIngressHost(runtimeName, headers)
20+
delete payload['CF_RUNTIME_NAME']
21+
}
22+
delete payload['CF_API_KEY']
23+
const qs = Object.entries(payload).map(kv => `${esc(kv[0])}=${esc(kv[1] || '')}`).join('&')
24+
const url = `${host}/app-proxy/api/image-report?${qs}`
25+
if (payload['CF_LOCAL']) {
26+
return { url: `${host}/api/image-report?${qs}`, headers }
27+
}
28+
return { url, headers }
3529
}
36-
return { url, headers }
37-
}
38-
3930

40-
export async function getRuntimeIngressHost(runtimeName: string, headers: Record<string, string>, platformHost = 'https://g.codefresh.io'): Promise<string> {
41-
const graphQLClient = new GraphQLClient(`${platformHost}/2.0/api/graphql`, {
42-
headers
43-
})
31+
static async getRuntimeIngressHost(runtimeName: string, headers: Record<string, string>, platformHost = 'https://g.codefresh.io'): Promise<string> {
32+
const graphQLClient = new GraphQLClient(`${platformHost}/2.0/api/graphql`, {
33+
headers
34+
})
4435

45-
const getRuntimeIngressHostQuery = gql`
46-
query Runtime($name: String!) {
47-
runtime(name: $name) {
48-
ingressHost
49-
}
50-
}`
36+
const getRuntimeIngressHostQuery = gql`
37+
query Runtime($name: String!) {
38+
runtime(name: $name) {
39+
ingressHost
40+
}
41+
}`
5142

52-
const res = await graphQLClient.request(getRuntimeIngressHostQuery, { name: runtimeName })
53-
const ingressHost = get(res, 'runtime.ingressHost')
54-
if (!ingressHost) {
55-
const message = res.runtime ? `ingress host is not defined on your '${runtimeName}' runtime` : `runtime '${runtimeName}' does not exist`
56-
throw new errors.ValidationError(`Validation Error: ${message}`)
43+
const res = await graphQLClient.request(getRuntimeIngressHostQuery, { name: runtimeName })
44+
const ingressHost = get(res, 'runtime.ingressHost')
45+
if (!ingressHost) {
46+
const message = res.runtime ? `ingress host is not defined on your '${runtimeName}' runtime` : `runtime '${runtimeName}' does not exist`
47+
throw new errors.ValidationError(`Validation Error: ${message}`)
48+
}
49+
return ingressHost
5750
}
58-
return ingressHost
59-
}
6051

61-
export const errors = {
62-
EventSourceError: class extends Error {
63-
constructor(message?: string, name?: string) {
64-
super(message)
65-
this.name = name || 'EventSourceError'
66-
}
67-
},
68-
ValidationError: class extends Error {
69-
constructor(message?: string, name?: string) {
70-
super(message)
71-
this.name = name || 'ValidationError'
52+
static tryParseJson = (str: string) => {
53+
try {
54+
return JSON.parse(str)
55+
} catch {
56+
return str
7257
}
7358
}
74-
}
59+
}
60+

src/validate.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { errors } from './utils'
1+
import { errors } from './errors'
22

33
/**
44
* Validate mandatory env vars. address host default

0 commit comments

Comments
 (0)