UNPKG

@tomino/dynamic-form-semantic-ui

Version:

Semantic UI form renderer based on dynamic form generation

90 lines 3.07 kB
import * as React from 'react'; import { Query } from 'react-apollo'; import gql from 'graphql-tag'; import { createComponents } from '../common'; import { observer } from 'mobx-react'; import { Context } from '../context'; import { simpleHandle } from '../helpers'; export function parseParameter(value, type) { switch (type) { case 'number': return parseFloat(value); case 'boolean': return value === 'true' ? true : false; } return value; } export function parseVariables(props, context) { const { owner, formElement: { props: { variables, boundVariables, onQuery } } } = props; let currentVariables = onQuery ? simpleHandle(props, onQuery, owner, context) : {}; if (variables) { for (let v of variables) { currentVariables[v.name] = parseParameter(v.value, v.type); } } if (boundVariables) { for (let v of boundVariables) { currentVariables[v.name] = owner.getValue(v.source); } } return currentVariables; } export const ApolloQuery = props => { const [error, setError] = React.useState(null); const context = React.useContext(Context); const { owner, formElement: { props: { query, loadingText, target, onError, onResult, propTarget } } } = props; if (!query) { return React.createElement("div", null, "Please specify the query"); } let parsedQuery; try { parsedQuery = gql([query]); } catch (ex) { return React.createElement("pre", null, "Query Error: ", ex.message); } let currentVariables = parseVariables(props, context); return (React.createElement(Query, { query: parsedQuery, variables: currentVariables, onCompleted: (data) => { if (target) { owner.setValue(target, data[Object.getOwnPropertyNames(data)[0]]); } if (onResult) { simpleHandle(props, onResult, context, data); } }, onError: (data) => { console.log(data); try { if (onError) { simpleHandle(props, onError, context, data); } if (error) { setError(null); } setError(data.message); } catch (ex) { setError(ex); } } }, ({ loading, error, data }) => { if (error) { return React.createElement("pre", null, "Query Error: ", JSON.stringify(error, null, 2)); } if (loading) return loadingText; if (error) return `Error! ${error.message}`; let dataProps = { ...props }; if (propTarget) { dataProps.dataProps = { [propTarget]: data[Object.getOwnPropertyNames(data)[0]] }; } return createComponents(dataProps); })); }; export const ApolloQueryView = { Component: observer(ApolloQuery) }; //# sourceMappingURL=apollo_query_view.js.map