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

65 lines
2 KiB
JavaScript
Raw Normal View History

import React, { Component } from "react";
import PropTypes from "prop-types";
import { graphql } from "react-apollo";
import gql from "graphql-tag";
import { getSetting, singleClientTemplate, Utils } from "meteor/vulcan:lib";
import { extractCollectionInfo, extractFragmentInfo } from "./handleOptions";
2018-06-05 11:51:25 +09:00
export default function withSingle(options) {
const { pollInterval = getSetting("pollInterval", 20000), enableCache = false, extraQueries } = options;
const { collectionName, collection } = extractCollectionInfo(options);
const { fragmentName, fragment } = extractFragmentInfo(options, 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
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,
enableCache
2018-06-05 12:12:04 +09: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;
}
});
}