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: initial version #1

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,24 @@
"prepare": "ts-patch install -s"
},
"dependencies": {
"@jsdevtools/ono": "^7.1.3",
"columnify": "^1.6.0",
"endent": "^2.1.0",
"express": "^4.17.2",
"express-serve-static-core": "^0.1.1",
"floggy": "^0.3.2",
"got": "^12.0.1",
"lodash": "^4.17.21",
"path-to-regexp": "^6.2.0",
"tslib": "^2.3.1"
},
"devDependencies": {
"@prisma-labs/prettier-config": "0.1.0",
"@types/body-parser": "^1.19.2",
"@types/columnify": "^1.5.1",
"@types/express": "^4",
"@types/express-serve-static-core": "^4.17.28",
"@types/lodash": "^4",
"@types/node": "17.0.13",
"@typescript-eslint/eslint-plugin": "5.11.0",
"@typescript-eslint/parser": "5.11.0",
Expand All @@ -57,6 +71,7 @@
"prettier": "2.5.1",
"ts-node": "10.5.0",
"ts-patch": "2.0.1",
"type-fest": "^2.11.1",
"typescript": "4.5.5",
"typescript-snapshots-plugin": "1.7.0",
"typescript-transform-paths": "3.3.1"
Expand Down
161 changes: 161 additions & 0 deletions src/client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
import { responseDefaults } from './server/endpoints/mock'
import { Expectation, ExpectationSettings, Scenario } from './types'
import ono from '@jsdevtools/ono'
import { deepInspect } from '~/helpers'
import columnify from 'columnify'
import endent from 'endent'
import got from 'got/dist/source'
import { merge } from 'lodash'
import { PartialDeep } from 'type-fest'

export type ClientSettings = {
scope: string
mode: Scenario['mode']
server: {
protocol: string
host: string
port: number
}
}

export class Client {
constructor(settings?: PartialDeep<ClientSettings>) {
this.settings(settings ?? {})
}
private expectations: Scenario['expectations'] = []

private _settings: ClientSettings = {
server: {
protocol: 'http',
host: `localhost`,
port: 9000,
},
scope: 'default',
mode: {
name: 'fixture',
},
}

add(expectations: ExpectationSettings | ExpectationSettings[]) {
if (!Array.isArray(expectations)) {
expectations = [expectations]
}

expectations.forEach((e) =>
this.expectations.push({
match: {
method: e.method ?? '*',
path: e.path ?? '*',
},
response: e.response ?? {},
hits: 0,
})
)
return this
}

reset() {
this.expectations = []
return this
}

/**
* Helpers
*/

settings(settings: PartialDeep<ClientSettings>) {
merge(this._settings, settings)
}

async start() {
await this.setScenario()
return this
}

async done() {
const scenario = await this.getScenario()

if (this._settings.mode.name === 'fixture') {
const unusedExpectations = scenario.expectations.filter((expectation) => expectation.hits === 0)

if (unusedExpectations.length > 0) {
throw new Error(
endent`
Mockapie scenario is expected to be done but is not. Mockapie expected the following requests but they never came:

${renderExpectations(unusedExpectations)}
`
)
}
} else {
if (scenario.expectations.length > 0) {
throw new Error(
endent`
Mockapie scenario is expected to be done but is not. Mockapie expected the following requests but they never came:

${renderExpectations(scenario.expectations)}
`
)
}
}
}

/**
* Internal API
*/

private async setScenario() {
await got
.post(
`${this._settings.server.protocol}://${this._settings.server.host}:${this._settings.server.port}/scenario/set`,
{
responseType: 'json',
json: {
scope: this._settings.scope,
scenario: {
expectations: this.expectations,
mode: this._settings.mode,
} as Scenario,
},
}
)
.catch((e) => {
throw ono(e, `Failed to set api mock scenario`)
})

return this
}

private async getScenario() {
const res = await got
.post<Scenario>(
`${this._settings.server.protocol}://${this._settings.server.host}:${this._settings.server.port}/scenario/get`,
{
responseType: 'json',
json: {
scope: this._settings.scope,
},
}
)
.catch((e) => {
throw ono(e, `Failed to get api mock scenario`)
})

return res.body
}
}

const renderExpectations = (x: Expectation[]) => {
return columnify(
x.map((_) => ({
match: deepInspect(_.match),
response: deepInspect({
..._.response,
...responseDefaults,
}),
})),
{
columnSplitter: ' ',
}
)
}
11 changes: 11 additions & 0 deletions src/helpers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import * as Util from 'util'

/**
* TypeScript helper to statically enforce that all cases have been handled in a switch (or similar) block.
*/
export const casesHandled = (x: never): never => {
// Should never happen, but in case it does :)
throw new Error(`All cases were not handled:\n${Util.inspect(x)}`)
}

export const deepInspect = (x: unknown) => Util.inspect(x, { depth: 20 })
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export * from '~/lib/utils'
export * as Mockapie from './index_'
4 changes: 4 additions & 0 deletions src/index_.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export * from './client'
export { serverLog } from './logger'
export * from './server/server'
export * from './types'
3 changes: 3 additions & 0 deletions src/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { log } from 'floggy'

export const serverLog = log.child('mockapi').child('server')
Loading