Vulcan/packages/vulcan-core/lib/modules/containers/withSingle.js

76 lines
2.2 KiB
JavaScript
Raw Normal View History

2018-01-06 07:07:38 +01:00
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';
2018-06-05 12:12:04 +09:00
import { getSetting, getFragment, getFragmentName, getCollection, singleClientTemplate, Utils } from 'meteor/vulcan:lib';
2018-06-05 11:51:25 +09:00
export default function withSingle(options) {
const {
collectionName,
pollInterval = getSetting('pollInterval', 20000),
enableCache = false,
extraQueries,
} = options;
2018-01-26 22:00:36 -06:00
const collection = options.collection || getCollection(collectionName);
2018-06-05 11:51:25 +09:00
const typeName = collection.options.typeName;
2018-06-05 12:12:04 +09:00
const resolverName = Utils.camelCaseify(typeName);
2018-06-05 11:51:25 +09:00
let fragment;
if (options.fragment) {
fragment = options.fragment;
} else if (options.fragmentName) {
fragment = getFragment(options.fragmentName);
} else {
fragment = getFragment(`${collection.options.collectionName}DefaultFragment`);
}
const fragmentName = getFragmentName(fragment);
const query = gql`${singleClientTemplate({ typeName, fragmentName, extraQueries })}${fragment}`;
2018-06-05 11:51:25 +09:00
return graphql(query, {
alias: `with${typeName}`,
options({ documentId, slug, selector = { documentId, slug } }) { // OpenCrud backwards compatibility
const graphQLOptions = {
2018-06-05 11:51:25 +09:00
variables: {
2018-06-05 12:12:04 +09:00
input: {
selector,
2018-06-05 12:12:04 +09:00
enableCache,
}
},
2017-01-11 10:36:08 +01:00
pollInterval, // note: pollInterval can be set to 0 to disable polling (20s by default)
};
if (options.fetchPolicy) {
graphQLOptions.fetchPolicy = options.fetchPolicy;
}
return graphQLOptions;
},
props: returnedProps => {
2018-01-25 15:03:03 -06:00
const { /* ownProps, */ data } = returnedProps;
2018-06-05 11:51:25 +09:00
const propertyName = options.propertyName || 'document';
const props = {
2017-05-03 14:42:57 +09:00
loading: data.loading,
// document: Utils.convertDates(collection, data[singleResolverName]),
2018-06-05 12:12:04 +09:00
[propertyName]: data[resolverName] && data[resolverName].result,
2016-11-23 11:07:48 +09:00
fragmentName,
fragment,
data,
};
if (data.error) {
// get graphQL error (see https://github.com/thebigredgeek/apollo-errors/issues/12)
props.error = data.error.graphQLErrors[0];
}
return props;
},
});
}