Debian Codegraph @

lib/route-handlers/function.js

raw
1 import BaseRouteHandler from "./base";
2 import assert from "../assert";
3 import { dasherize } from "../utils/inflector";
4
5 /**
6 * @hide
7 */
8 export default class FunctionRouteHandler extends BaseRouteHandler {
9 constructor(schema, serializerOrRegistry, userFunction, path, server) {
10 super(server);
11 this.schema = schema;
12 this.serializerOrRegistry = serializerOrRegistry;
13 this.userFunction = userFunction;
14 this.path = path;
15 }
16
17 handle(request) {
18 return this.userFunction(this.schema, request);
19 }
20
21 setRequest(request) {
22 this.request = request;
23 }
24
25 serialize(response, serializerType) {
26 let serializer;
27
28 if (serializerType) {
29 serializer = this.serializerOrRegistry.serializerFor(serializerType, {
30 explicit: true,
31 });
32 } else {
33 serializer = this.serializerOrRegistry;
34 }
35
36 return serializer.serialize(response, this.request);
37 }
38
39 normalizedRequestAttrs(modelName = null) {
40 let {
41 path,
42 request,
43 request: { requestHeaders },
44 } = this;
45 let attrs;
46
47 let lowerCaseHeaders = {};
48 for (let header in requestHeaders) {
49 lowerCaseHeaders[header.toLowerCase()] = requestHeaders[header];
50 }
51 if (/x-www-form-urlencoded/.test(lowerCaseHeaders["content-type"])) {
52 attrs = this._getAttrsForFormRequest(request);
53 } else {
54 if (modelName) {
55 assert(
56 dasherize(modelName) === modelName,
57 `You called normalizedRequestAttrs('${modelName}'), but normalizedRequestAttrs was intended to be used with the dasherized version of the model type. Please change this to normalizedRequestAttrs('${dasherize(
58 modelName
59 )}').`
60 );
61 } else {
62 modelName = this.getModelClassFromPath(path);
63 }
64
65 assert(
66 this.schema.hasModelForModelName(modelName),
67 `You're using a shorthand or the #normalizedRequestAttrs helper but the detected model of '${modelName}' does not exist. You might need to pass in the correct modelName as the first argument to #normalizedRequestAttrs.`
68 );
69
70 attrs = this._getAttrsForRequest(request, modelName);
71 }
72
73 return attrs;
74 }
75 }