yapi/client/components/Postman/Postman.js

621 lines
21 KiB
JavaScript
Raw Normal View History

2017-08-22 09:43:33 +08:00
import React, { Component } from 'react'
import PropTypes from 'prop-types'
2017-08-24 10:44:02 +08:00
import { Button, Input, Select, Card, Alert, Spin, Icon, Collapse, Radio, Tooltip, message } from 'antd'
2017-08-22 09:43:33 +08:00
import { autobind } from 'core-decorators';
import crossRequest from 'cross-request';
2017-08-24 12:13:44 +08:00
import mockEditor from '../../containers/Project/Interface/InterfaceList/mockEditor'
2017-08-22 09:43:33 +08:00
import URL from 'url';
2017-08-24 12:13:44 +08:00
import './Postman.scss'
2017-08-22 09:43:33 +08:00
2017-08-24 21:07:49 +08:00
const { TextArea } = Input;
2017-08-22 09:43:33 +08:00
const InputGroup = Input.Group;
const Option = Select.Option;
const Panel = Collapse.Panel;
const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;
export default class Run extends Component {
static propTypes = {
2017-08-23 11:41:46 +08:00
data: PropTypes.object,
2017-08-24 10:44:02 +08:00
save: PropTypes.func,
saveTip: PropTypes.string,
type: PropTypes.string
2017-08-22 09:43:33 +08:00
}
state = {
2017-08-24 21:07:49 +08:00
res: {},
resHeader: {},
2017-08-22 09:43:33 +08:00
method: 'GET',
domains: [],
pathname: '',
query: [],
bodyForm: [],
headers: [],
currDomain: '',
2017-08-29 10:08:55 +08:00
caseEnv: '',
2017-08-22 09:43:33 +08:00
bodyType: '',
2017-08-24 17:02:39 +08:00
bodyOther: '',
isDidMount: false
2017-08-22 09:43:33 +08:00
}
constructor(props) {
super(props)
}
componentWillMount() {
this.getInterfaceState()
}
componentWillReceiveProps(nextProps) {
2017-08-23 14:59:24 +08:00
if (nextProps.data._id !== this.props.data._id) {
this.getInterfaceState(nextProps)
}
2017-08-22 09:43:33 +08:00
}
2017-08-24 17:02:39 +08:00
componentDidMount() {
2017-08-24 17:15:58 +08:00
const { bodyType } = this.state;
2017-08-24 21:07:49 +08:00
if(bodyType && bodyType !== 'file' && bodyType !== 'form') {
2017-08-24 17:15:58 +08:00
this.loadBodyEditor()
}
2017-08-24 17:02:39 +08:00
}
2017-08-22 09:43:33 +08:00
@autobind
getInterfaceState(nextProps) {
const props = nextProps || this.props;
2017-08-24 10:44:02 +08:00
const { data, type } = props;
2017-08-22 09:43:33 +08:00
const {
method = '',
path: url = '',
req_headers = [],
req_body_type,
req_query = [],
req_params = [],
req_body_other = '',
req_body_form = [],
basepath = '',
2017-08-23 11:41:46 +08:00
env = [],
2017-08-29 10:08:55 +08:00
case_env = ''
2017-08-22 09:43:33 +08:00
} = data;
2017-08-24 10:44:02 +08:00
// case 任意编辑 pathname不管项目的 basepath
const pathname = (type === 'inter' ? (basepath + url) : url).replace(/\/+/g, '/');
2017-08-22 09:43:33 +08:00
2017-08-29 10:08:55 +08:00
// let hasContentType = false;
// req_headers.forEach(headerItem => {
// // TODO 'Content-Type' 排除大小写不同格式影响
// if (headerItem.name === 'Content-Type'){
// hasContentType = true;
// headerItem.value = headerItem.value || 'application/x-www-form-urlencoded';
// }
// })
// if (!hasContentType) {
// req_headers.push({name: 'Content-Type', value: 'application/x-www-form-urlencoded'});
// }
// const domains = env.concat();
// if (domain && !env.find(item => item.domain === domain)) {
// domains.push({name: 'default', domain})
// }
2017-08-22 09:43:33 +08:00
this.setState({
method,
2017-08-29 10:08:55 +08:00
domains: env.concat(),
2017-08-22 09:43:33 +08:00
pathParam: req_params.concat(),
pathname,
query: req_query.concat(),
bodyForm: req_body_form.concat(),
headers: req_headers.concat(),
bodyOther: req_body_other,
2017-08-29 10:08:55 +08:00
caseEnv: case_env || (env[0] && env[0].name),
2017-08-22 09:43:33 +08:00
bodyType: req_body_type || 'form',
loading: false
2017-08-24 17:15:58 +08:00
}, () => {
2017-08-24 21:07:49 +08:00
if(req_body_type && req_body_type !== 'file' && req_body_type !== 'form') {
2017-08-24 17:15:58 +08:00
this.loadBodyEditor()
}
2017-08-22 09:43:33 +08:00
});
}
@autobind
reqRealInterface() {
const { headers, bodyForm, bodyOther, currDomain, method, pathname, query, bodyType } = this.state;
const urlObj = URL.parse(currDomain);
const href = URL.format({
protocol: urlObj.protocol || 'http',
host: urlObj.host,
pathname,
query: this.getQueryObj(query)
});
this.setState({ loading: true })
crossRequest({
url: href,
method,
headers: this.getHeadersObj(headers),
data: bodyType === 'form' ? this.arrToObj(bodyForm) : bodyOther,
files: bodyType === 'form' ? this.getFiles(bodyForm) : {},
2017-08-24 10:44:02 +08:00
success: (res, header) => {
2017-08-24 12:13:44 +08:00
try {
res = typeof res === 'object' ? res : JSON.parse(res)
header = typeof header === 'object' ? header : JSON.parse(header)
} catch (e) {
message.error(e.message)
}
2017-08-24 10:44:02 +08:00
message.success('请求完成')
this.setState({res, resHeader: header})
2017-08-22 09:43:33 +08:00
this.setState({ loading: false })
2017-08-24 12:13:44 +08:00
this.bindAceEditor()
2017-08-22 09:43:33 +08:00
},
2017-08-24 10:44:02 +08:00
error: (err, header) => {
2017-08-24 12:13:44 +08:00
try {
err = typeof err === 'object' ? err : JSON.parse(err)
header = typeof header === 'object' ? header : JSON.parse(header)
} catch (e) {
message.error(e.message)
}
2017-08-24 10:44:02 +08:00
message.success('请求完成')
this.setState({res: err || '请求失败', resHeader: header})
2017-08-22 09:43:33 +08:00
this.setState({ loading: false })
2017-08-24 12:13:44 +08:00
this.bindAceEditor()
2017-08-22 09:43:33 +08:00
}
})
}
@autobind
changeDomain(value) {
this.setState({ currDomain: value });
}
@autobind
selectDomain(value) {
2017-08-29 10:08:55 +08:00
this.setState({ caseEnv: value });
2017-08-22 09:43:33 +08:00
}
@autobind
changeHeader(e, index, isName) {
const headers = JSON.parse(JSON.stringify(this.state.headers));
const v = e.target.value;
if (isName) {
headers[index].name = v;
} else {
headers[index].value = v;
}
this.setState({ headers });
}
@autobind
addHeader() {
const { headers } = this.state;
this.setState({headers: headers.concat([{name: '', value: ''}])})
}
@autobind
deleteHeader(index) {
const { headers } = this.state;
this.setState({headers: headers.filter((item, i) => +index !== +i)});
}
@autobind
setContentType(type) {
const headersObj = this.getHeadersObj(this.state.headers);
headersObj['Content-Type'] = type;
this.setState({headers: this.objToArr(headersObj)})
}
@autobind
changeQuery(e, index, isKey) {
const query = JSON.parse(JSON.stringify(this.state.query));
const v = e.target.value;
if (isKey) {
query[index].name = v;
} else {
query[index].value = v;
}
this.setState({ query });
}
@autobind
addQuery() {
const { query } = this.state;
this.setState({query: query.concat([{name: '', value: ''}])})
}
@autobind
deleteQuery(index) {
const { query } = this.state;
this.setState({query: query.filter((item, i) => +index !== +i)});
}
@autobind
changePathParam(e, index, isKey) {
const pathParam = JSON.parse(JSON.stringify(this.state.pathParam));
const v = e.target.value;
const name = pathParam[index].name;
let newPathname = this.state.pathname;
if (isKey) {
if (!name && v) {
newPathname += `/:${v}`;
} else {
newPathname = newPathname.replace(`/:${name}`, v ? `/:${v}` : '')
}
pathParam[index].name = v;
} else {
pathParam[index].value = v;
}
this.setState({ pathParam, pathname: newPathname });
}
@autobind
addPathParam() {
const { pathParam } = this.state;
this.setState({pathParam: pathParam.concat([{name: '', value: ''}])})
}
@autobind
deletePathParam(index) {
const { pathParam } = this.state;
const name = pathParam[index].name;
const newPathname = this.state.pathname.replace(`/:${name}`, '');
this.setState({pathParam: pathParam.filter((item, i) => +index !== +i), pathname: newPathname});
}
@autobind
changeBody(e, index, type) {
const bodyForm = JSON.parse(JSON.stringify(this.state.bodyForm));
switch (type) {
case 'key':
bodyForm[index].name = e.target.value
break;
case 'type':
bodyForm[index].type = e
break;
case 'value':
if (bodyForm[index].type === 'file') {
bodyForm[index].value = e.target.id
} else {
bodyForm[index].value = e.target.value
}
break;
default:
break;
}
if (type === 'type' && e === 'file') {
this.setContentType('multipart/form-data')
}
this.setState({ bodyForm });
}
@autobind
addBody() {
const { bodyForm } = this.state;
this.setState({bodyForm: bodyForm.concat([{name: '', value: '', type: 'text'}])})
}
@autobind
deleteBody(index) {
const { bodyForm } = this.state;
this.setState({bodyForm: bodyForm.filter((item, i) => +index !== +i)});
}
@autobind
changeMethod(value) {
this.setState({ method: value });
}
@autobind
changePath(e) {
const path = e.target.value;
const urlObj = URL.parse(path, true);
this.setState({
query: this.objToArr(urlObj.query),
pathname: urlObj.pathname
})
}
@autobind
changeBodyType(value) {
2017-08-24 17:02:39 +08:00
this.setState({bodyType: value}, () => {
if(value !== 'file' && value !== 'form') {
this.loadBodyEditor()
}
})
2017-08-22 09:43:33 +08:00
}
hasCrossRequestPlugin() {
const dom = document.getElementById('y-request');
return dom.getAttribute('key') === 'yapi';
}
objToArr(obj, key, value) {
const keyName = key || 'name';
const valueName = value || 'value';
const arr = []
Object.keys(obj).forEach((_key) => {
if (_key) {
arr.push({[keyName]: _key, [valueName]: obj[_key]});
}
})
return arr;
}
arrToObj(arr) {
const obj = {};
arr.forEach(item => {
if (item.name && item.type !== 'file') {
obj[item.name] = item.value || '';
}
})
return obj;
}
getFiles(bodyForm) {
const files = {};
bodyForm.forEach(item => {
if (item.name && item.type === 'file') {
files[item.name] = item.value
}
})
return files;
}
getQueryObj(query) {
const queryObj = {};
query.forEach(item => {
if (item.name) {
queryObj[item.name] = item.value || '';
}
})
return queryObj;
}
getHeadersObj(headers) {
const headersObj = {};
headers.forEach(item => {
if (item.name && item.value) {
headersObj[item.name] = item.value;
}
})
return headersObj;
}
2017-08-24 12:13:44 +08:00
bindAceEditor = () => {
mockEditor({
container: 'res-body-pretty',
data: JSON.stringify(this.state.res, null, 2),
readOnly:true,
onChange: function () {}
})
mockEditor({
container: 'res-headers-pretty',
data: JSON.stringify(this.state.resHeader, null, 2),
readOnly:true,
onChange: function () {}
})
}
2017-08-24 17:02:39 +08:00
loadBodyEditor = () => {
const that = this;
setTimeout(function() {
mockEditor({
container: 'body-other-edit',
data: that.state.bodyOther,
onChange: function (d) {
if (d.format !== true) return false;
that.setState({
bodyOther: d.text
})
}
})
}, 0);
}
2017-08-24 12:13:44 +08:00
2017-08-22 09:43:33 +08:00
@autobind
fileChange(e, index) {
console.log(e)
console.log(index)
}
render () {
2017-08-29 10:08:55 +08:00
const { method, domains, pathParam, pathname, query, headers, bodyForm, caseEnv, bodyType, resHeader } = this.state;
2017-08-22 09:43:33 +08:00
const hasPlugin = this.hasCrossRequestPlugin();
2017-08-25 09:49:02 +08:00
const isResJson = resHeader && resHeader['content-type'] && resHeader['content-type'].indexOf('application/json') !== -1
2017-08-22 09:43:33 +08:00
let path = pathname;
pathParam.forEach(item => {
path = path.replace(`:${item.name}`, item.value || `:${item.name}`);
});
const search = decodeURIComponent(URL.format({query: this.getQueryObj(query)}));
return (
2017-08-24 12:13:44 +08:00
<div className="interface-test postman">
2017-08-22 09:43:33 +08:00
<div className="has-plugin">
{
hasPlugin ? '' :
<Alert
message={
<div>
2017-08-28 19:50:08 +08:00
温馨提示当前正在使用接口测试服务请安装我们为您免费提供的测试增强插件&nbsp;该插件可支持任何 chrome 内核的浏览器
2017-08-25 10:28:46 +08:00
<div>
<a
target="blank"
href="https://chrome.google.com/webstore/detail/cross-request/cmnlfmgbjmaciiopcgodlhpiklaghbok?hl=en-US"
> [Google 商店获取需翻墙]</a>
</div>
<div>
<a
target="blank"
2017-08-28 19:50:08 +08:00
href="/attachment/cross-request.zip"
> [手动下载] </a>
<span> zip 文件解压后将 crx 文件拖入到 chrome://extensions/ </span>
2017-08-25 10:28:46 +08:00
<a
target="blank"
href="http://www.jianshu.com/p/12ca04c61fc6"
2017-08-28 19:50:08 +08:00
> [详细安装教程] </a>
2017-08-25 10:28:46 +08:00
</div>
2017-08-22 09:43:33 +08:00
</div>
}
type="warning"
/>
}
</div>
<Card title="请求部分" noHovering className="req-part">
<div className="url">
<InputGroup compact style={{display: 'flex'}}>
2017-08-28 15:47:57 +08:00
<Select disabled value={method} style={{flexBasis: 60}} onChange={this.changeMethod} >
2017-08-22 09:43:33 +08:00
<Option value="GET">GET</Option>
<Option value="POST">POST</Option>
</Select>
2017-08-29 10:08:55 +08:00
<Select value={caseEnv} style={{flexBasis: 180, flexGrow: 1}} onSelect={this.selectDomain}>
2017-08-22 09:43:33 +08:00
{
2017-08-29 10:08:55 +08:00
domains.map((item, index) => (<Option value={item.name} key={index}>{item.name + '' + item.domain}</Option>))
2017-08-22 09:43:33 +08:00
}
</Select>
2017-08-28 15:47:57 +08:00
<Input disabled value={path + search} onChange={this.changePath} spellCheck="false" style={{flexBasis: 180, flexGrow: 1}} />
2017-08-22 09:43:33 +08:00
</InputGroup>
<Tooltip placement="bottom" title="请求真实接口">
<Button
2017-08-25 11:29:43 +08:00
disabled={!hasPlugin}
2017-08-22 09:43:33 +08:00
onClick={this.reqRealInterface}
type="primary"
style={{marginLeft: 10}}
loading={this.state.loading}
>发送</Button>
</Tooltip>
2017-08-23 15:50:07 +08:00
<Tooltip placement="bottom" title={this.props.saveTip}>
2017-08-22 09:43:33 +08:00
<Button
2017-08-23 11:41:46 +08:00
onClick={this.props.save}
2017-08-22 09:43:33 +08:00
type="primary"
2017-08-24 10:44:02 +08:00
style={{marginLeft: 10}}
>{this.props.type === 'inter' ? '保存' : '更新'}</Button>
2017-08-22 09:43:33 +08:00
</Tooltip>
</div>
<Collapse defaultActiveKey={['0', '1', '2', '3']} bordered={true}>
2017-08-28 16:12:57 +08:00
<Panel header="PATH PARAMETERS" key="0" className={pathParam.length === 0 ? 'hidden' : ''}>
2017-08-22 09:43:33 +08:00
{
pathParam.map((item, index) => {
return (
<div key={index} className="key-value-wrap">
2017-08-28 15:47:57 +08:00
<Input disabled value={item.name} onChange={e => this.changePathParam(e, index, true)} className="key" />
2017-08-22 09:43:33 +08:00
<span className="eq-symbol">=</span>
<Input value={item.value} onChange={e => this.changePathParam(e, index)} className="value" />
2017-08-28 15:47:57 +08:00
<Icon style={{display: 'none'}} type="delete" className="icon-btn" onClick={() => this.deletePathParam(index)} />
2017-08-22 09:43:33 +08:00
</div>
)
})
}
2017-08-28 15:47:57 +08:00
<Button style={{display: 'none'}} type="primary" icon="plus" onClick={this.addPathParam}>添加Path参数</Button>
2017-08-22 09:43:33 +08:00
</Panel>
2017-08-28 16:12:57 +08:00
<Panel header="QUERY PARAMETERS" key="1" className={query.length === 0 ? 'hidden' : ''}>
2017-08-22 09:43:33 +08:00
{
query.map((item, index) => {
return (
<div key={index} className="key-value-wrap">
2017-08-28 15:47:57 +08:00
<Input disabled value={item.name} onChange={e => this.changeQuery(e, index, true)} className="key" />
2017-08-22 09:43:33 +08:00
<span className="eq-symbol">=</span>
<Input value={item.value} onChange={e => this.changeQuery(e, index)} className="value" />
2017-08-28 15:47:57 +08:00
<Icon style={{display: 'none'}} type="delete" className="icon-btn" onClick={() => this.deleteQuery(index)} />
2017-08-22 09:43:33 +08:00
</div>
)
})
}
2017-08-28 15:47:57 +08:00
<Button style={{display: 'none'}} type="primary" icon="plus" onClick={this.addQuery}>添加Query参数</Button>
2017-08-22 09:43:33 +08:00
</Panel>
2017-08-28 16:12:57 +08:00
<Panel header="HEADERS" key="2" className={headers.length === 0 ? 'hidden' : ''}>
2017-08-22 09:43:33 +08:00
{
headers.map((item, index) => {
return (
<div key={index} className="key-value-wrap">
2017-08-28 15:47:57 +08:00
<Input disabled value={item.name} onChange={e => this.changeHeader(e, index, true)} className="key" />
2017-08-22 09:43:33 +08:00
<span className="eq-symbol">=</span>
<Input value={item.value} onChange={e => this.changeHeader(e, index)} className="value" />
2017-08-28 15:47:57 +08:00
<Icon style={{display: 'none'}} type="delete" className="icon-btn" onClick={() => this.deleteHeader(index)} />
2017-08-22 09:43:33 +08:00
</div>
)
})
}
2017-08-28 15:47:57 +08:00
<Button style={{display: 'none'}} type="primary" icon="plus" onClick={this.addHeader}>添加Header</Button>
2017-08-22 09:43:33 +08:00
</Panel>
<Panel
header={
<div style={{display: 'flex', justifyContent: 'space-between'}}>
<div>BODY</div>
<div onClick={e => e.stopPropagation()} style={{marginRight: 5}}>
2017-08-28 15:47:57 +08:00
<Select disabled value={bodyType !== 'form' && bodyType !== 'file' ? 'text' : bodyType} onChange={this.changeBodyType} className={method === 'POST' ? '' : 'none'}>
2017-08-22 09:43:33 +08:00
<Option value="text">Text</Option>
<Option value="file">File</Option>
<Option value="form">Form</Option>
</Select>
</div>
</div>
}
key="3"
2017-08-28 16:12:57 +08:00
className={method === 'POST' ? '' : 'hidden'}
2017-08-22 09:43:33 +08:00
>
{ method === 'POST' && bodyType !== 'form' && bodyType !== 'file' &&
<div>
2017-08-28 15:47:57 +08:00
<RadioGroup disabled value={bodyType} onChange={(e) => this.changeBodyType(e.target.value)}>
2017-08-22 09:43:33 +08:00
<RadioButton value="json">JSON</RadioButton>
<RadioButton value="text">TEXT</RadioButton>
<RadioButton value="xml">XML</RadioButton>
</RadioGroup>
2017-08-24 17:02:39 +08:00
<div id="body-other-edit" style={{marginTop: 10}} className="pretty-editor"></div>
2017-08-22 09:43:33 +08:00
</div>
}
{
method === 'POST' && bodyType === 'form' &&
<div>
{
bodyForm.map((item, index) => {
return (
<div key={index} className="key-value-wrap">
2017-08-28 15:47:57 +08:00
<Input disabled value={item.name} onChange={e => this.changeBody(e, index, 'key')} className="key" />
2017-08-22 09:43:33 +08:00
<span>[</span>
2017-08-28 15:47:57 +08:00
<Select disabled value={item.type} onChange={e => this.changeBody(e, index, 'type')}>
2017-08-22 09:43:33 +08:00
<Option value="file">File</Option>
<Option value="text">Text</Option>
</Select>
<span>]</span>
<span className="eq-symbol">=</span>
{
item.type === 'file' ? <Input type="file" id={'file_' + index} onChange={e => this.changeBody(e, index, 'value')} multiple className="value" /> :
<Input value={item.value} onChange={e => this.changeBody(e, index, 'value')} className="value" />
}
2017-08-28 15:47:57 +08:00
<Icon style={{display: 'none'}} type="delete" className="icon-btn" onClick={() => this.deleteBody(index)} />
2017-08-22 09:43:33 +08:00
</div>
)
})
}
2017-08-28 15:47:57 +08:00
<Button style={{display: 'none'}} type="primary" icon="plus" onClick={this.addBody}>添加Form参数</Button>
2017-08-22 09:43:33 +08:00
</div>
}
{
method === 'POST' && bodyType === 'file' &&
<div>
<Input type="file"></Input>
</div>
}
2017-08-28 16:12:57 +08:00
{/*
2017-08-22 09:43:33 +08:00
method !== 'POST' &&
<div>GET 请求没有 BODY</div>
2017-08-28 16:12:57 +08:00
*/}
2017-08-22 09:43:33 +08:00
</Panel>
</Collapse>
</Card>
<Card title="返回结果" noHovering className="resp-part">
<Spin spinning={this.state.loading}>
2017-08-24 10:44:02 +08:00
<div className="res-code"></div>
<Collapse defaultActiveKey={['0', '1']} bordered={true}>
<Panel header="BODY" key="0" >
2017-08-24 21:07:49 +08:00
<div id="res-body-pretty" className="pretty-editor" style={{display: isResJson ? '' : 'none'}}></div>
<TextArea
style={{display: isResJson ? 'none' : ''}}
2017-08-22 09:43:33 +08:00
value={typeof this.state.res === 'object' ? JSON.stringify(this.state.res, null, 2) : this.state.res.toString()}
2017-08-24 10:44:02 +08:00
autosize={{ minRows: 2, maxRows: 10 }}
2017-08-24 21:07:49 +08:00
></TextArea>
2017-08-24 10:44:02 +08:00
</Panel>
<Panel header="HEADERS" key="1" >
2017-08-24 12:13:44 +08:00
{/*<TextArea
2017-08-24 10:44:02 +08:00
value={typeof this.state.resHeader === 'object' ? JSON.stringify(this.state.resHeader, null, 2) : this.state.resHeader.toString()}
autosize={{ minRows: 2, maxRows: 10 }}
2017-08-24 12:13:44 +08:00
></TextArea>*/}
2017-08-24 17:02:39 +08:00
<div id="res-headers-pretty" className="pretty-editor"></div>
2017-08-24 10:44:02 +08:00
</Panel>
</Collapse>
2017-08-22 09:43:33 +08:00
</Spin>
</Card>
</div>
)
}
}