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

77 lines
1.9 KiB
JavaScript
Raw Normal View History

2018-01-28 22:24:33 -06:00
/*
Generic mutation wrapper to upsert a document in a collection.
2018-01-28 22:24:33 -06:00
Sample mutation:
2018-01-28 22:24:33 -06:00
mutation upsertMovie($input: UpsertMovieInput) {
upsertMovie(input: $input) {
data {
_id
name
__typename
}
__typename
2018-01-28 22:24:33 -06:00
}
}
Arguments:
2018-01-28 22:24:33 -06:00
- input
- input.selector: a selector to indicate the document to update
- input.data: the document (set a field to `null` to delete it)
2018-01-28 22:24:33 -06:00
Child Props:
2018-01-28 22:24:33 -06:00
- upsertMovie({ selector, data })
*/
2018-01-28 22:24:33 -06:00
import React, { Component } from 'react';
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';
import { upsertClientTemplate } from 'meteor/vulcan:core';
import clone from 'lodash/clone';
2018-01-28 22:24:33 -06:00
import { extractCollectionInfo, extractFragmentInfo } from 'meteor/vulcan:lib';
const withUpsert = options => {
const { collectionName, collection } = extractCollectionInfo(options);
const { fragmentName, fragment } = extractFragmentInfo(options, collectionName);
2018-01-28 22:24:33 -06:00
const typeName = collection.options.typeName;
const query = gql`
${upsertClientTemplate({ typeName, fragmentName })}
${fragment}
`;
2018-01-28 22:24:33 -06:00
return graphql(query, {
alias: `withUpsert${typeName}`,
2018-01-28 22:24:33 -06:00
props: ({ ownProps, mutate }) => ({
[`upsert${typeName}`]: args => {
const { selector, data } = args;
return mutate({
variables: { selector, data }
// note: updateQueries is not needed for editing documents
});
},
// OpenCRUD backwards compatibility
upsertMutation: args => {
2018-06-14 23:00:28 +09:00
const { selector, set, unset } = args;
const data = clone(set);
unset &&
Object.keys(unset).forEach(fieldName => {
data[fieldName] = null;
});
return mutate({
variables: { selector, data }
// note: updateQueries is not needed for editing documents
2018-01-28 22:24:33 -06:00
});
}
})
2018-01-28 22:24:33 -06:00
});
};
2018-01-28 22:24:33 -06:00
export default withUpsert;