Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
114 changes: 114 additions & 0 deletions packages/server/src/api/rpc/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,26 @@ import { loggerSchema } from '../common/schemas';
import { processSuperJsonRequestPayload, unmarshalQ } from '../common/utils';
Comment thread
jiashengguo marked this conversation as resolved.
import { log, registerCustomSerializers } from '../utils';

const TRANSACTION_ROUTE_PREFIX = '$transaction' as const;
const VALID_OPS = new Set([
'create',
'createMany',
'createManyAndReturn',
'upsert',
'findFirst',
'findUnique',
'findMany',
'aggregate',
'groupBy',
'count',
'exists',
'update',
'updateMany',
'updateManyAndReturn',
'delete',
'deleteMany',
]);
Comment thread
jiashengguo marked this conversation as resolved.
Outdated

registerCustomSerializers();

/**
Expand Down Expand Up @@ -71,6 +91,15 @@ export class RPCApiHandler<Schema extends SchemaDef = SchemaDef> implements ApiH
});
}

if (model === TRANSACTION_ROUTE_PREFIX) {
return this.handleTransaction({
client,
method: method.toUpperCase(),
type: op,
requestBody,
Comment thread
jiashengguo marked this conversation as resolved.
});
}
Comment thread
jiashengguo marked this conversation as resolved.

model = lowerCaseFirst(model);
method = method.toUpperCase();
let args: unknown;
Expand Down Expand Up @@ -185,6 +214,91 @@ export class RPCApiHandler<Schema extends SchemaDef = SchemaDef> implements ApiH
}
}

private async handleTransaction({
client,
method,
type,
requestBody,
}: {
client: ClientContract<Schema>;
method: string;
type: string;
requestBody?: unknown;
}): Promise<Response> {
if (method !== 'POST') {
return this.makeBadInputErrorResponse('invalid request method, only POST is supported');
}

if (type !== 'sequential') {
return this.makeBadInputErrorResponse(`unsupported transaction type: ${type}`);
}

if (!requestBody || !Array.isArray(requestBody) || requestBody.length === 0) {
return this.makeBadInputErrorResponse('request body must be a non-empty array of operations');
}

const processedOps: Array<{ model: string; op: string; args: unknown }> = [];

for (let i = 0; i < requestBody.length; i++) {
const item = requestBody[i];
if (!item || typeof item !== 'object') {
return this.makeBadInputErrorResponse(`operation at index ${i} must be an object`);
}
const { model: itemModel, op: itemOp, args: itemArgs } = item as any;
if (!itemModel || typeof itemModel !== 'string') {
return this.makeBadInputErrorResponse(`operation at index ${i} is missing a valid "model" field`);
}
if (!itemOp || typeof itemOp !== 'string') {
return this.makeBadInputErrorResponse(`operation at index ${i} is missing a valid "op" field`);
}
if (!VALID_OPS.has(itemOp)) {
return this.makeBadInputErrorResponse(`operation at index ${i} has invalid op: ${itemOp}`);
}
if (!this.isValidModel(client, lowerCaseFirst(itemModel))) {
return this.makeBadInputErrorResponse(`operation at index ${i} has unknown model: ${itemModel}`);
}
if (itemArgs !== undefined && itemArgs !== null && typeof itemArgs !== 'object') {
return this.makeBadInputErrorResponse(`operation at index ${i} has invalid "args" field`);
}
Comment thread
jiashengguo marked this conversation as resolved.
Outdated

const { result: processedArgs, error: argsError } = await this.processRequestPayload(itemArgs ?? {});
if (argsError) {
return this.makeBadInputErrorResponse(`operation at index ${i}: ${argsError}`);
}
processedOps.push({ model: lowerCaseFirst(itemModel), op: itemOp, args: processedArgs });
}

try {
const promises = processedOps.map(({ model, op, args }) => {
return (client as any)[model][op](args);
});

log(this.options.log, 'debug', () => `handling "$transaction" request with ${promises.length} operations`);

const clientResult = await client.$transaction(promises as any);

const { json, meta } = SuperJSON.serialize(clientResult);
const responseBody: any = { data: json };
if (meta) {
responseBody.meta = { serialization: meta };
}

const response = { status: 200, body: responseBody };
log(
this.options.log,
'debug',
() => `sending response for "$transaction" request: ${safeJSONStringify(response)}`,
);
return response;
} catch (err) {
log(this.options.log, 'error', `error occurred when handling "$transaction" request`, err);
if (err instanceof ORMError) {
return this.makeORMErrorResponse(err);
}
return this.makeGenericErrorResponse(err);
}
}

private async handleProcedureRequest({
client,
method,
Expand Down
Loading
Loading