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

67 lines
1.5 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:
mutation createMovie($data: CreateMovieData) {
createMovie(data: $data) {
data {
_id
name
__typename
}
__typename
}
}
Arguments:
- data: the document to insert
Child Props:
- createMovie({ data })
*/
import React, { Component } from 'react';
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';
import { createClientTemplate } from 'meteor/vulcan:core';
import { extractCollectionInfo, extractFragmentInfo } from './handleOptions';
const withCreate = options => {
const { collectionName, collection } = extractCollectionInfo(options);
const { fragmentName, fragment } = extractFragmentInfo(options, collectionName);
const typeName = collection.options.typeName;
const 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;
return mutate({
variables: { data }
2018-06-02 18:49:53 +09:00
});
},
// OpenCRUD backwards compatibility
newMutation: args => {
const { document } = args;
return mutate({
variables: { data: document }
});
}
})
});
};
export default withCreate;