Skip to content

Commit

Permalink
feat: Using OpenAPI schema in rest & express
Browse files Browse the repository at this point in the history
  • Loading branch information
simonas-notcat authored and mirceanis committed Sep 7, 2020
1 parent 719959a commit 80d0bad
Show file tree
Hide file tree
Showing 13 changed files with 2,133 additions and 106 deletions.
4 changes: 2 additions & 2 deletions __tests__/restAgent.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ const agent = createAgent<
plugins: [
new AgentRestClient({
url: 'http://localhost:' + port + '/agent',
enabledMethods: Object.keys(supportedMethods),
enabledMethods: supportedMethods,
}),
],
})
Expand Down Expand Up @@ -116,7 +116,7 @@ const setup = async (): Promise<boolean> => {

const agentRouter = AgentRouter({
getAgentForRequest: async req => serverAgent,
exposedMethods: serverAgent.availableMethods(),
exposedMethods: supportedMethods,
})

return new Promise((resolve, reject) => {
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
"json-schema": "^0.2.5",
"lerna": "^3.20.2",
"lerna-changelog": "^1.0.1",
"openapi-types": "^7.0.0",
"prettier": "^1.19.1",
"pretty-quick": "^2.0.1",
"rimraf": "^3.0.2",
Expand Down
32 changes: 13 additions & 19 deletions packages/daf-express/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { IAgent } from 'daf-core'
import { Request, Response, NextFunction, Router, json } from 'express'
import { supportedMethods, IAgentRESTMethod } from 'daf-rest'
import { supportedMethods } from 'daf-rest'
import Debug from 'debug'

interface RequestWithAgent extends Request {
Expand All @@ -10,7 +10,7 @@ interface RequestWithAgent extends Request {
export const AgentRouter = (options: {
getAgentForRequest: (req: Request) => Promise<IAgent>
exposedMethods: string[]
overrides?: Record<string, IAgentRESTMethod>
extraMethods?: Array<string>
}): Router => {
const router = Router()
router.use(json())
Expand All @@ -19,27 +19,21 @@ export const AgentRouter = (options: {
next()
})

const allMethods: Record<string, IAgentRESTMethod> = { ...supportedMethods, ...options.overrides }
const allMethods: Array<string> = supportedMethods.concat(options.extraMethods ? options.extraMethods : [])

for (const exposedMethod of options.exposedMethods) {
const method = allMethods[exposedMethod]
if (!method) throw Error('Method not supported: ' + exposedMethod)
if (!allMethods.includes(exposedMethod)) throw Error('Method not supported: ' + exposedMethod)
Debug('daf:express:initializing')(exposedMethod)

switch (method.type) {
case 'POST':
router.post(method.path, async (req: RequestWithAgent, res: Response, next: NextFunction) => {
if (!req.agent) throw Error('Agent not available')
try {
const result = await req.agent.execute(exposedMethod, req.body)
res.status(200).json(result)
} catch (e) {
res.status(500).json({ error: e.message })
}
})
break
// TODO: handle GET
}
router.post('/' + exposedMethod, async (req: RequestWithAgent, res: Response, next: NextFunction) => {
if (!req.agent) throw Error('Agent not available')
try {
const result = await req.agent.execute(exposedMethod, req.body)
res.status(200).json(result)
} catch (e) {
res.status(500).json({ error: e.message })
}
})
}

return router
Expand Down
1 change: 1 addition & 0 deletions packages/daf-rest/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
},
"devDependencies": {
"@types/debug": "^4.1.5",
"openapi-types": "^7.0.0",
"typescript": "^3.8.3"
},
"files": [
Expand Down
17 changes: 17 additions & 0 deletions packages/daf-rest/src/__tests__/client.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { AgentRestClient, supportedMethods } from '../'

describe('daf-rest', () => {
it('should support some methods', () => {
expect(Array.isArray(supportedMethods)).toEqual(true)
expect(supportedMethods.length).toBeGreaterThan(0)
})

it('should be a valid agent plugin', () => {
const client = new AgentRestClient({
url: 'mock',
enabledMethods: supportedMethods,
})

expect(client.methods[supportedMethods[0]]).toBeTruthy()
})
})
16 changes: 8 additions & 8 deletions packages/daf-rest/src/client.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { IAgentPlugin, IPluginMethodMap } from 'daf-core'
import { supportedMethods } from './methods'
import { IAgentRESTMethod } from './types'
import { supportedMethods } from './index'

export class AgentRestClient implements IAgentPlugin {
readonly methods: IPluginMethodMap = {}
Expand All @@ -10,19 +9,20 @@ export class AgentRestClient implements IAgentPlugin {
url: string
enabledMethods: string[]
headers?: Record<string, string>
overrides?: Record<string, IAgentRESTMethod>
extraMethods?: Array<string>
}) {
this.url = options.url

const allMethods: Record<string, IAgentRESTMethod> = { ...supportedMethods, ...options.overrides }
const allMethods: Array<string> = supportedMethods.concat(
options.extraMethods ? options.extraMethods : [],
)

for (const method of options.enabledMethods) {
if (allMethods[method]) {
if (allMethods.includes(method)) {
this.methods[method] = async (args: any) => {
// TODO: handle GET
const res = await fetch(this.url + allMethods[method].path, {
const res = await fetch(this.url + '/' + method, {
headers: { ...options.headers, 'Content-Type': 'application/json' },
method: allMethods[method].type,
method: 'post',
body: JSON.stringify(args),
})
const json = await res.json()
Expand Down
5 changes: 3 additions & 2 deletions packages/daf-rest/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export { AgentRestClient } from './client'
export { supportedMethods } from './methods'
export * from './types'
import { openApiSchema } from './openApiSchema'
export { openApiSchema }
export const supportedMethods = Object.keys(openApiSchema.paths).map(path => path.slice(1))
57 changes: 0 additions & 57 deletions packages/daf-rest/src/methods.ts

This file was deleted.

Loading

0 comments on commit 80d0bad

Please sign in to comment.