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

59 lines
1.6 KiB
JavaScript
Raw Normal View History

/*
Generic mutation wrapper to insert a new document in a collection and update
a related query on the client with the new item and a new total item count.
Sample mutation:
2018-06-02 18:49:53 +09:00
mutation updateMovie($document: MoviesInput) {
updateMovie(document: $document) {
...MovieFormFragment
}
}
Arguments:
- document: the document to insert
Child Props:
2018-06-02 18:49:53 +09:00
- createMovie(document)
*/
import React, { Component } from 'react';
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';
import { getFragment, getFragmentName, getCollection, createClientTemplate } from 'meteor/vulcan:core';
2018-06-02 18:49:53 +09:00
export default function withCreate(options) {
2018-01-27 18:53:28 -07:00
const { collectionName } = options;
// get options
2018-01-27 18:53:28 -07:00
const collection = options.collection || getCollection(collectionName),
fragment = options.fragment || getFragment(options.fragmentName || `${collectionName}DefaultFragment`),
fragmentName = getFragmentName(fragment),
typeName = collection.options.typeName,
query = gql`${createClientTemplate({ typeName, fragmentName })}${fragment}`;
// wrap component with graphql HoC
return graphql(query, {
2018-06-02 18:49:53 +09:00
alias: `withCreate${typeName}`,
props: ({ownProps, mutate}) => ({
[`create${typeName}`]: (args) => {
const { data } = args;
2018-06-02 18:49:53 +09:00
return mutate({
variables: { input: { data } },
2018-06-02 18:49:53 +09:00
});
},
// OpenCRUD backwards compatibility
newMutation: (args) => {
const { document } = args;
return mutate({
variables: { input: { data: document } },
});
}
}),
});
2016-11-27 08:39:25 +09:00
}