You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

68 lines
1.6KB

  1. import Armpits from "@sniff/armpits";
  2. import express from "express";
  3. import config from "./config";
  4. import middleware from "./middleware/index";
  5. import { CreateLink } from "./utils/database";
  6. import { ErrorResponse } from "./utils/generators";
  7. const app = express();
  8. app.use(express.json());
  9. app.use(middleware.database);
  10. app.use(middleware.log);
  11. app.get("/", async (req, res) => {
  12. return res.redirect(config.mainDomain);
  13. });
  14. app.get("/all", async (req, res) => {
  15. let links = [];
  16. req.db.list({ include_docs: true }).then((body) => {
  17. body.rows.forEach((row) => {
  18. delete row.doc._id;
  19. delete row.doc._rev;
  20. links.push(row.doc);
  21. });
  22. res.json(links);
  23. });
  24. });
  25. app.post("/", middleware.lock, async (req, res) => {
  26. try {
  27. let { target, code } = req.body;
  28. if (!target)
  29. return res
  30. .status(400)
  31. .send({ success: false, error: ErrorResponse("MISSING_TARGET") });
  32. let Link = await CreateLink({ target, code });
  33. return res.send(Link);
  34. } catch (error) {
  35. res.send({
  36. success: false,
  37. error: ErrorResponse(error.message),
  38. });
  39. }
  40. });
  41. app.get("/:code", async (req, res) => {
  42. try {
  43. let response = await req.db.get(req.params.code);
  44. res.redirect(301, response.target);
  45. } catch (error) {
  46. switch (error.message) {
  47. case "missing":
  48. return res.send({
  49. success: false,
  50. error: ErrorResponse("MISSING_CODE"),
  51. });
  52. default:
  53. return res.send({ success: false, error: { msg: error } });
  54. }
  55. }
  56. });
  57. app.listen(config.port, () => {
  58. Armpits.plus(
  59. `${config.domain.replace(/https?:\/\//, "")} | Listening on port`,
  60. config.port
  61. );
  62. });