Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save AugustoCalaca/05993413eb7a20521756ca1d401f22af to your computer and use it in GitHub Desktop.
Save AugustoCalaca/05993413eb7a20521756ca1d401f22af to your computer and use it in GitHub Desktop.
createEditSingleFieldMutation function that generate an edit single field mutation for a given model
import { GraphQLID, GraphQLNonNull, GraphQLNullableType } from 'graphql';
import { mutationWithClientMutationId } from 'graphql-relay';
import { Model } from 'mongoose';
import { errorField } from '../fields/errorField';
import { successField } from '../fields/successField';
import { getObjectId } from '../getObjectId';
type MutationArgs = {
id: string;
};
type CreateEditSingleFieldArgs<Context> = {
name: string;
model: Model<any>;
clearCache: (context: Context, id: string) => void;
notFoundMessage: (context: Context) => string;
successMessage: (context: Context) => string;
fieldName: string;
fieldType: GraphQLNullableType;
outputFields: object;
process: (args: MutationArgs, context: Context, item: Model<any>) => Promise<void>;
};
export const createEditSingleFieldMutation = <Context extends object>({
name,
model,
clearCache,
notFoundMessage,
successMessage,
fieldName,
fieldType,
outputFields,
process,
}: CreateEditSingleFieldArgs<Context>) => {
const mutation = mutationWithClientMutationId({
name,
inputFields: {
id: {
type: GraphQLNonNull(GraphQLID),
},
[fieldName]: {
type: GraphQLNonNull(fieldType),
},
},
mutateAndGetPayload: async (args: MutationArgs, context: Context) => {
const item = await model.findOne({
_id: getObjectId(args.id),
});
if (!item) {
return {
error: notFoundMessage ? notFoundMessage(context) : context.t('Item not found'),
};
}
await model.updateOne(
{
_id: item._id,
},
{
$set: {
[fieldName]: args[fieldName],
},
},
);
clearCache(context, item._id);
if (process) {
await process(args, context, item);
}
return {
id: item._id,
error: null,
success: successMessage ? successMessage(context) : context.t('Successfully edited'),
};
},
outputFields: {
...errorField,
...successField,
...outputFields,
},
});
return mutation;
};
const mutation = createEditSingleFieldMutation({
name: 'UserEditName',
model: User,
fieldName: 'title',
fieldType: GraphQLString,
clearCache: UserLoader.clearCache,
notFoundMessage: ({ t }) => t('User not found'),
successMessage: ({ t }) => t('User edited successfully'),
outputFields: {
user: {
type: UserType,
resolve: ({ id }, _, context) => UserLoader.load(context, id),
},
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment