in with the new

This commit is contained in:
Ron
2017-03-17 21:17:53 -07:00
parent bd8344c808
commit f22a628934
157 changed files with 12952 additions and 0 deletions

View File

@@ -0,0 +1,234 @@
import YAML from "js-yaml"
import serializeError from "serialize-error"
// Actions conform to FSA (flux-standard-actions)
// {type: string,payload: Any|Error, meta: obj, error: bool}
export const UPDATE_SPEC = "spec_update_spec"
export const UPDATE_URL = "spec_update_url"
export const UPDATE_JSON = "spec_update_json"
export const UPDATE_PARAM = "spec_update_param"
export const VALIDATE_PARAMS = "spec_validate_param"
export const SET_RESPONSE = "spec_set_response"
export const SET_REQUEST = "spec_set_request"
export const LOG_REQUEST = "spec_log_request"
export const CLEAR_RESPONSE = "spec_clear_response"
export const CLEAR_REQUEST = "spec_clear_request"
export const ClEAR_VALIDATE_PARAMS = "spec_clear_validate_param"
export const UPDATE_OPERATION_VALUE = "spec_update_operation_value"
export const UPDATE_RESOLVED = "spec_update_resolved"
export const SET_SCHEME = "set_scheme"
export function updateSpec(spec) {
if(spec instanceof Error) {
return {type: UPDATE_SPEC, error: true, payload: spec}
}
if(typeof spec === "string") {
return {
type: UPDATE_SPEC,
payload: spec.replace(/\t/g, " ") || ""
}
}
return {
type: UPDATE_SPEC,
payload: ""
}
}
export function updateResolved(spec) {
return {
type: UPDATE_RESOLVED,
payload: spec
}
}
export function updateUrl(url) {
return {type: UPDATE_URL, payload: url}
}
export function updateJsonSpec(json) {
if(!json || typeof json !== "object") {
throw new Error("updateJson must only accept a simple JSON object")
}
return {type: UPDATE_JSON, payload: json}
}
export const parseToJson = (str) => ({specActions, specSelectors, errActions}) => {
let { specStr } = specSelectors
let json = null
try {
str = str || specStr()
errActions.clear({ source: "parser" })
json = YAML.safeLoad(str)
} catch(e) {
// TODO: push error to state
console.error(e)
return errActions.newSpecErr({
source: "parser",
level: "error",
message: e.reason,
line: e.mark && e.mark.line ? e.mark.line + 1 : undefined
})
}
return specActions.updateJsonSpec(json)
}
export const resolveSpec = (json, url) => ({specActions, specSelectors, errActions, fn: { fetch, resolve, AST }}) => {
if(typeof(json) === "undefined") {
json = specSelectors.specJson()
}
if(typeof(url) === "undefined") {
url = specSelectors.url()
}
let { getLineNumberForPath } = AST
let specStr = specSelectors.specStr()
return resolve({fetch, spec: json, baseDoc: url})
.then( ({spec, errors}) => {
errActions.clear({
type: "thrown"
})
if(errors.length > 0) {
let preparedErrors = errors
.map(err => {
console.error(err)
err.line = err.fullPath ? getLineNumberForPath(specStr, err.fullPath) : null
err.path = err.fullPath ? err.fullPath.join(".") : null
err.level = "error"
err.type = "thrown"
err.source = "resolver"
Object.defineProperty(err, "message", { enumerable: true, value: err.message })
return err
})
errActions.newThrownErrBatch(preparedErrors)
}
return specActions.updateResolved(spec)
})
}
export const formatIntoYaml = () => ({specActions, specSelectors}) => {
let { specStr } = specSelectors
let { updateSpec } = specActions
try {
let yaml = YAML.safeDump(YAML.safeLoad(specStr()), {indent: 2})
updateSpec(yaml)
} catch(e) {
updateSpec(e)
}
}
export function changeParam( path, paramName, value, isXml ){
return {
type: UPDATE_PARAM,
payload:{ path, value, paramName, isXml }
}
}
export function validateParams( payload ){
return {
type: VALIDATE_PARAMS,
payload:{ pathMethod: payload }
}
}
export function clearValidateParams( payload ){
return {
type: ClEAR_VALIDATE_PARAMS,
payload:{ pathMethod: payload }
}
}
export function changeConsumesValue(path, value) {
return {
type: UPDATE_OPERATION_VALUE,
payload:{ path, value, key: "consumes_value" }
}
}
export function changeProducesValue(path, value) {
return {
type: UPDATE_OPERATION_VALUE,
payload:{ path, value, key: "produces_value" }
}
}
export const setResponse = ( path, method, res ) => {
return {
payload: { path, method, res },
type: SET_RESPONSE
}
}
export const setRequest = ( path, method, req ) => {
return {
payload: { path, method, req },
type: SET_REQUEST
}
}
// This is for debugging, remove this comment if you depend on this action
export const logRequest = (req) => {
return {
payload: req,
type: LOG_REQUEST
}
}
// Actually fire the request via fn.execute
// (For debugging) and ease of testing
export const executeRequest = (req) => ({fn, specActions, errActions}) => {
let { pathName, method } = req
let parsedRequest = Object.assign({}, req)
if ( pathName && method ) {
parsedRequest.operationId = method.toLowerCase() + "-" + pathName
}
parsedRequest = fn.buildRequest(parsedRequest)
specActions.setRequest(req.pathName, req.method, parsedRequest)
return fn.execute(req)
.then( fn.serializeRes )
.then( res => specActions.setResponse(req.pathName, req.method, res))
.catch( err => specActions.setResponse(req.pathName, req.method, { error: true, err: serializeError(err) } ) )
}
// I'm using extras as a way to inject properties into the final, `execute` method - It's not great. Anyone have a better idea? @ponelat
export const execute = ( { path, method, ...extras }={} ) => (system) => {
let { fn:{fetch}, specSelectors, specActions } = system
let spec = specSelectors.spec().toJS()
let scheme = specSelectors.operationScheme(path, method)
let { requestContentType, responseContentType } = specSelectors.contentTypeValues([path, method]).toJS()
let isXml = /xml/i.test(requestContentType)
let parameters = specSelectors.parameterValues([path, method], isXml).toJS()
return specActions.executeRequest({fetch, spec, pathName: path, method, parameters, requestContentType, scheme, responseContentType, ...extras })
}
export function clearResponse (path, method) {
return {
type: CLEAR_RESPONSE,
payload:{ path, method }
}
}
export function clearRequest (path, method) {
return {
type: CLEAR_REQUEST,
payload:{ path, method }
}
}
export function setScheme (scheme, path, method) {
return {
type: SET_SCHEME,
payload: { scheme, path, method }
}
}

View File

@@ -0,0 +1,17 @@
import reducers from "./reducers"
import * as actions from "./actions"
import * as selectors from "./selectors"
import * as wrapActions from "./wrap-actions"
export default function() {
return {
statePlugins: {
spec: {
wrapActions,
reducers,
actions,
selectors
}
}
}
}

View File

@@ -0,0 +1,123 @@
import { fromJS } from "immutable"
import { fromJSOrdered, validateParam } from "core/utils"
import win from "../../window"
import {
UPDATE_SPEC,
UPDATE_URL,
UPDATE_JSON,
UPDATE_PARAM,
VALIDATE_PARAMS,
SET_RESPONSE,
SET_REQUEST,
UPDATE_RESOLVED,
UPDATE_OPERATION_VALUE,
CLEAR_RESPONSE,
CLEAR_REQUEST,
ClEAR_VALIDATE_PARAMS,
SET_SCHEME
} from "./actions"
export default {
[UPDATE_SPEC]: (state, action) => {
return (typeof action.payload === "string")
? state.set("spec", action.payload)
: state
},
[UPDATE_URL]: (state, action) => {
return state.set("url", action.payload+"")
},
[UPDATE_JSON]: (state, action) => {
return state.set("json", fromJSOrdered(action.payload))
},
[UPDATE_RESOLVED]: (state, action) => {
return state.setIn(["resolved"], fromJSOrdered(action.payload))
},
[UPDATE_PARAM]: ( state, {payload} ) => {
let { path, paramName, value, isXml } = payload
return state.updateIn( [ "resolved", "paths", ...path, "parameters" ], fromJS([]), parameters => {
let index = parameters.findIndex( p => p.get( "name" ) === paramName )
if (!(value instanceof win.File)) {
value = fromJSOrdered( value )
}
return parameters.setIn( [ index, isXml ? "value_xml" : "value" ], value)
})
},
[VALIDATE_PARAMS]: ( state, { payload: { pathMethod } } ) => {
let operation = state.getIn( [ "resolved", "paths", ...pathMethod ] )
let parameters = operation.get("parameters")
let isXml = /xml/i.test(operation.get("consumes_value"))
return state.updateIn( [ "resolved", "paths", ...pathMethod, "parameters" ], fromJS([]), parameters => {
return parameters.withMutations( parameters => {
for ( let i = 0, len = parameters.count(); i < len; i++ ) {
let errors = validateParam(parameters.get(i), isXml)
parameters.setIn([i, "errors"], fromJS(errors))
}
})
})
},
[ClEAR_VALIDATE_PARAMS]: ( state, { payload: { pathMethod } } ) => {
let operation = state.getIn( [ "resolved", "paths", ...pathMethod ] )
let parameters = operation.get("parameters")
return state.updateIn( [ "resolved", "paths", ...pathMethod, "parameters" ], fromJS([]), parameters => {
return parameters.withMutations( parameters => {
for ( let i = 0, len = parameters.count(); i < len; i++ ) {
parameters.setIn([i, "errors"], fromJS({}))
}
})
})
},
[SET_RESPONSE]: (state, { payload: { res, path, method } } ) =>{
let result
if ( res.error ) {
result = Object.assign({error: true}, res.err)
} else {
result = res
}
let newState = state.setIn( [ "responses", path, method ], fromJSOrdered(result) )
// ImmutableJS messes up Blob. Needs to reset its value.
if (res.data instanceof win.Blob) {
newState = newState.setIn( [ "responses", path, method, "text" ], res.data)
}
return newState
},
[SET_REQUEST]: (state, { payload: { req, path, method } } ) =>{
return state.setIn( [ "requests", path, method ], fromJSOrdered(req))
},
[UPDATE_OPERATION_VALUE]: (state, { payload: { path, value, key } }) => {
return state.setIn(["resolved", "paths", ...path, key], fromJS(value))
},
[CLEAR_RESPONSE]: (state, { payload: { path, method } } ) =>{
return state.deleteIn( [ "responses", path, method ])
},
[CLEAR_REQUEST]: (state, { payload: { path, method } } ) =>{
return state.deleteIn( [ "requests", path, method ])
},
[SET_SCHEME]: (state, { payload: { scheme, path, method } } ) =>{
if ( path && method ) {
return state.setIn( [ "scheme", path, method ], scheme)
}
if (!path && !method) {
return state.setIn( [ "scheme", "_defaultScheme" ], scheme)
}
}
}

View File

@@ -0,0 +1,318 @@
import { createSelector } from "reselect"
import { fromJS, Set, Map, List } from "immutable"
const DEFAULT_TAG = "default"
const OPERATION_METHODS = ["get", "put", "post", "delete", "options", "head", "patch"]
const state = state => {
return state || Map()
}
export const lastError = createSelector(
state,
spec => spec.get("lastError")
)
export const url = createSelector(
state,
spec => spec.get("url")
)
export const specStr = createSelector(
state,
spec => spec.get("spec") || ""
)
export const specSource = createSelector(
state,
spec => spec.get("specSource") || "not-editor"
)
export const specJson = createSelector(
state,
spec => spec.get("json", Map())
)
export const specResolved = createSelector(
state,
spec => spec.get("resolved", Map())
)
// Default Spec ( as an object )
export const spec = state => {
let res = specResolved(state)
if(res.count() < 1)
res = specJson(state)
return res
}
export const info = createSelector(
spec,
spec => returnSelfOrNewMap(spec && spec.get("info"))
)
export const externalDocs = createSelector(
spec,
spec => returnSelfOrNewMap(spec && spec.get("externalDocs"))
)
export const version = createSelector(
info,
info => info && info.get("version")
)
export const semver = createSelector(
version,
version => /v?([0-9]*)\.([0-9]*)\.([0-9]*)/i.exec(version).slice(1)
)
export const paths = createSelector(
spec,
spec => spec.get("paths")
)
export const operations = createSelector(
paths,
paths => {
if(!paths || paths.size < 1)
return List()
let list = List()
if(!paths || !paths.forEach) {
return List()
}
paths.forEach((path, pathName) => {
if(!path || !path.forEach) {
return {}
}
path.forEach((operation, method) => {
if(OPERATION_METHODS.indexOf(method) === -1) {
return
}
list = list.push(fromJS({
path: pathName,
method,
operation,
id: `${method}-${pathName}`
}))
})
})
return list
}
)
export const consumes = createSelector(
spec,
spec => Set(spec.get("consumes"))
)
export const produces = createSelector(
spec,
spec => Set(spec.get("produces"))
)
export const security = createSelector(
spec,
spec => spec.get("security", List())
)
export const securityDefinitions = createSelector(
spec,
spec => spec.get("securityDefinitions")
)
export const findDefinition = ( state, name ) => {
return specResolved(state).getIn(["definitions", name], null)
}
export const definitions = createSelector(
spec,
spec => spec.get("definitions") || Map()
)
export const basePath = createSelector(
spec,
spec => spec.get("basePath")
)
export const host = createSelector(
spec,
spec => spec.get("host")
)
export const schemes = createSelector(
spec,
spec => spec.get("schemes", Map())
)
export const operationsWithRootInherited = createSelector(
operations,
consumes,
produces,
(operations, consumes, produces) => {
return operations.map( ops => ops.update("operation", op => {
if(op) {
if(!Map.isMap(op)) { return }
return op.withMutations( op => {
if ( !op.get("consumes") ) {
op.update("consumes", a => Set(a).merge(consumes))
}
if ( !op.get("produces") ) {
op.update("produces", a => Set(a).merge(produces))
}
return op
})
} else {
// return something with Immutable methods
return Map()
}
}))
}
)
export const tags = createSelector(
spec,
json => json.get("tags", List())
)
export const tagDetails = (state, tag) => {
let currentTags = tags(state) || List()
return currentTags.filter(Map.isMap).find(t => t.get("name") === tag, Map())
}
export const operationsWithTags = createSelector(
operationsWithRootInherited,
operations => {
return operations.reduce( (taggedMap, op) => {
let tags = Set(op.getIn(["operation","tags"]))
if(tags.count() < 1)
return taggedMap.update(DEFAULT_TAG, List(), ar => ar.push(op))
return tags.reduce( (res, tag) => res.update(tag, List(), (ar) => ar.push(op)), taggedMap )
}, Map())
}
)
export const taggedOperations = createSelector(
state,
operationsWithTags,
(state, tagMap) => {
return tagMap.map((ops, tag) => Map({tagDetails: tagDetails(state, tag), operations: ops}))
}
)
export const responses = createSelector(
state,
state => state.get( "responses", Map() )
)
export const requests = createSelector(
state,
state => state.get( "requests", Map() )
)
export const responseFor = (state, path, method) => {
return responses(state).getIn([path, method], null)
}
export const requestFor = (state, path, method) => {
return requests(state).getIn([path, method], null)
}
export const allowTryItOutFor = (state, path, method ) => {
// This is just a hook for now.
return true
}
// Get the parameter value by parameter name
export function getParameter(state, pathMethod, name) {
let params = spec(state).getIn(["paths", ...pathMethod, "parameters"], fromJS([]))
return params.filter( (p) => {
return Map.isMap(p) && p.get("name") === name
}).first()
}
export const hasHost = createSelector(
spec,
spec => {
const host = spec.get("host")
return typeof host === "string" && host.length > 0 && host[0] !== "/"
}
)
// Get the parameter values, that the user filled out
export function parameterValues(state, pathMethod, isXml) {
let params = spec(state).getIn(["paths", ...pathMethod, "parameters"], fromJS([]))
return params.reduce( (hash, p) => {
let value = isXml && p.get("in") === "body" ? p.get("value_xml") : p.get("value")
return hash.set(p.get("name"), value)
}, fromJS({}))
}
// True if any parameter includes `in: ?`
export function parametersIncludeIn(parameters, inValue="") {
if(List.isList(parameters)) {
return parameters.some( p => Map.isMap(p) && p.get("in") === inValue )
}
}
// True if any parameter includes `type: ?`
export function parametersIncludeType(parameters, typeValue="") {
if(List.isList(parameters)) {
return parameters.some( p => Map.isMap(p) && p.get("type") === typeValue )
}
}
// Get the consumes/produces value that the user selected
export function contentTypeValues(state, pathMethod) {
let op = spec(state).getIn(["paths", ...pathMethod], fromJS({}))
const parameters = op.get("parameters") || new List()
const requestContentType = (
parametersIncludeType(parameters, "file") ? "multipart/form-data"
: parametersIncludeIn(parameters, "formData") ? "application/x-www-form-urlencoded"
: op.get("consumes_value")
)
return fromJS({
requestContentType,
responseContentType: op.get("produces_value")
})
}
// Get the consumes/produces by path
export function operationConsumes(state, pathMethod) {
return spec(state).getIn(["paths", ...pathMethod, "consumes"], fromJS({}))
}
export const operationScheme = ( state, path, method ) => {
return state.getIn(["scheme", path, method]) || state.getIn(["scheme", "_defaultScheme"]) || "http"
}
export const canExecuteScheme = ( state, path, method ) => {
return ["http", "https"].indexOf(operationScheme(state, path, method)) > -1
}
export const validateBeforeExecute = ( state, pathMethod ) => {
let params = spec(state).getIn(["paths", ...pathMethod, "parameters"], fromJS([]))
let isValid = true
params.forEach( (p) => {
let errors = p.get("errors")
if ( errors && errors.count() ) {
isValid = false
}
})
return isValid
}
function returnSelfOrNewMap(obj) {
// returns obj if obj is an Immutable map, else returns a new Map
return Map.isMap(obj) ? obj : new Map()
}

View File

@@ -0,0 +1,15 @@
export const updateSpec = (ori, {specActions}) => (...args) => {
ori(...args)
specActions.parseToJson(...args)
}
export const updateJsonSpec = (ori, {specActions}) => (...args) => {
ori(...args)
specActions.resolveSpec(...args)
}
// Log the request ( just for debugging, shouldn't affect prod )
export const executeRequest = (ori, { specActions }) => (req) => {
specActions.logRequest(req)
return ori(req)
}