aboutsummaryrefslogtreecommitdiff
path: root/laurali/decorators.ts
blob: 54a0c79c2a2ee4ab6cb1348e9d201ca64d11ac14 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// This file is part of Laurali <https://github.com/gemrest/laurali>.
// Copyright (C) 2022-2022 Fuwn <[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, version 3.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright (C) 2022-2022 Fuwn <[email protected]>
// SPDX-License-Identifier: GPL-3.0-only

import { Hook } from "./hooks.ts";

/**
 * Mark the function as a route and register it to the `Server`.
 * @param path If the path is not provided, the function name will be used.
 */
export const route = (path?: string) => {
  return (
    // deno-lint-ignore no-explicit-any
    target: any,
    key: string | symbol,
    descriptor: PropertyDescriptor,
  ) => {
    target.addRoute(path || key, descriptor.value);

    return descriptor;
  };
};

/**
 * Mark the function as a hook and register it to the `Server`.
 * @param hook The type of hook which the function will be called for.
 */
export const hook = (hook?: Hook) => {
  return (
    // deno-lint-ignore no-explicit-any
    target: any,
    key: string | symbol,
    descriptor: PropertyDescriptor,
  ) => {
    let type;

    if (hook) {
      type = hook;
    } else {
      switch (key) {
        case "onPreRoute":
          {
            type = Hook.ON_PRE_ROUTE;
          }
          break;
        case "onPostRoute":
          {
            type = Hook.ON_POST_ROUTE;
          }
          break;
        case "onError":
          {
            type = Hook.ON_ERROR;
          }
          break;
        default: {
          throw new Error(
            `Unknown hook type: '${key.toString()}'. Did you forget to ` +
              "specify the hook type?`",
          );
        }
      }
    }

    target.addHook(type, descriptor.value);

    return descriptor;
  };
};