Mutation
Mutations respond to POST requests and are responsible for updating, creating, or deleting data. When a mutation is requested from the client, the associated resolve function is invoked.
The resolve function receives { input, ctx }
, where input represents the actual input for the mutation, and ctx represents the context, which could be the root context or another context if the resolver creating the mutation utilizes middleware.
Input validation is performed by the input schema, ensuring that the provided data adheres to specified constraints. Similarly, the output of the resolver, returned from the resolve function, is validated by the output schema.
If input validation fails, the PtsqError throws a BAD_REQUEST error, providing details about the validation error within the info property as a Typebox validation schema error result.
Similarly, if output validation fails, the PtsqError throws an INTERNAL_SERVER_ERROR error, again including information about the validation error within the info property.
These error-handling mechanisms ensure robustness and reliability in handling input and output data, allowing for precise identification and reporting of validation errors to clients.
import { PtsqServer } from '@ptsq/server';
import { Type } from '@sinclair/typebox';
import express, { Request, Response } from 'express';
const app = express();
const createContext = ({ req, res }: { req: Request; res: Response }) => ({
req,
res,
});
const { resolver, router, serve } = PtsqServer.init({
ctx: createContext,
}).create();
const testMutation = resolver
.args(Type.Object({ name: Type.String() }))
.output(Type.String())
.mutation(async ({ input /* { name: string } */ }) /* string */ => {
return `Hello, ${input.name}`;
});
const baseRouter = router({
test: testMutation,
});
export type BaseRouter = typeof baseRouter;
app.use((req, res) =>
serve({ router: baseRouter, ctx: { req, res } })(req, res),
);
app.listen(4000);