美文网首页
2022-09-12

2022-09-12

作者: Zeayal | 来源:发表于2022-09-12 18:31 被阅读0次
const express = require("express");
const morgan = require("morgan");
const { nanoid } = require("nanoid");
const yup = require("yup");
const monk = require("monk");
const app = express();
const fs = require("fs");
const path = require("path");
const fetch = require("node-fetch");
require("dotenv").config();

// const db = monk(process.env.MONGODB_URL);
// const db = monk('mongodb://mongo:27017/docker-node-mongo');
const db = monk('mongo:27017/db_short_url');
db.then(() => {
  console.log('mongodb connected');
}).catch(error => {
  console.log('monogodb error', error)
})
const urls = db.get("urls");
urls.createIndex({ slug: 1 }, { unique: true });

app.use(
  morgan(":method :url :status :res[content-length] - :response-time ms")
);
app.use(express.json());
app.use(express.static("public"));

app.get("/github", async (req, res, next) => {
  const response = await fetch("https://api.github.com/users/zeayal");
  console.log("response", response.ok);
  const data = await response.json();
  res.json({
    status: 0,
    data,
  });
});

app.use(
  "/scripts",
  express.static(__dirname + "/node_modules/@pnotify/")
);
app.use(
  "/style",
  express.static(__dirname + "/node_modules/@pnotify/")
);

const schema = yup.object().shape({
  url: yup.string().trim().url().required(),
  slug: yup
    .string()
    .trim()
    .matches(/^[\w\-]+$/i),
});

const slugSchema = yup.object().shape({
  slug: yup
    .string()
    .trim()
    .matches(/^[\w\-]+$/i),
});

const notFoundPath = path.resolve("public/404.html");

app.get("/:id", async (req, res, next) => {
  let { id: slug } = req.params;
  console.log("req.query", req.query);
  console.log("req.params", req.params);
  try {
    const valid = await slugSchema.validate({ slug });
    if (valid) {
      const data = await urls.findOne({ slug });
      res.redirect(data.url);
    } else {
      res.status(404).sendFile(notFoundPath);
    }
  } catch (e) {
    res.status(404).sendFile(notFoundPath);
  }
});

app.post("/url", async (req, res, next) => {
  let { url, slug } = req.body;
  console.log( url, slug );
  try {
    if (!slug) {
      slug = nanoid(5);
    }
    const valid = await schema.validate({ url, slug });
    if (valid) {
      const existing = await urls.findOne({ slug });
      if (existing) {
        throw new Error("Slug in use. 🍔");
      }
      const data = await urls.insert({
        url,
        slug,
      });

      res.json({
        status: 0,
        data,
        message: "新增成功",
      });
    }
  } catch (error) {
    next(error);
  }
});

app.get('/hello', (req,res) => {
  res.send(`hello, I'm in docker`);
})

app.use((error, req, res, next) => {
  if (error.status) {
    res.status(500);
  } else {
    res.status(500);
  }
  console.log('error.stack', error.stack);
  res.json({
    status: 1,
    // message: process.env.NODE_ENV === "production" ? "🍔" : error.stack,
    message:  error.stack,
  });
});

const PORT = process.env.PORT || 3000;

app.listen(PORT, () => {
  console.log(`server is runing in: http://localhost:${PORT}`);
});

相关文章

  • 学英语Prime Minister Liz Truss’s st

    2022-09-12 We are all devastated by the news we have just...

  • 幽人独自省,以待使君来

    是谁说的? 2022-09-12 在隆冬,我终于知道,我身上有一个不可战胜的夏天。

  • 第九篇《我和儿子的第一份协议》向优秀孟母堂研究生张蕊老师学习~抄

    2018-12-22 作者:张蕊老师 摘抄时间:2022-09-12 摘抄人:梁淑艳 今天,我和儿子签订了一份协议...

  • 月亮是我们平凡生活中最美的诗意

    原创 木渔石 老石说话 2022-09-12 12:06 发表于甘肃 十五的月亮十六圆,昨晚你看月亮了吗? 城里不...

  • 一个数学家的故事

    2022-09-12加德纳的 智能的结构 第7章 逻辑-数学智能 举例了一个如下的数学家故事。意在说明:有抱负的数...

  • 104|假期余额不足

    2022-09-12 星期一 晴 今天是假期最后一天,感觉时间过得很快,忙的时候总是希望时间过的飞慢! 但是时间是...

  • 双宝趣事3则

    双宝趣事3则 2022-09-12 周一 晴 1 心心对幼儿园仍是抗拒的。 鉴于心心在园不睡午觉的情况,老师交待假...

  • 难得的一家出游

    幸福日志2022-09-12 周一 晴 很久没有带公婆出去玩了,难得在淮南的周边出现一个农村游玩项目,本来一起同行...

  • 2022-09-12

    我是因为你,才得以穿越这黑暗的。——《把你交给时间》 1 如果没有遇见你。 我是否还能如现在般,对着电脑,书籍,笔...

  • 2022-09-12

    闲来无事多愁思。 昨天闺密中午忙完后,给我发了一个“郁闷”的表情包,我回复,有我在。 于是我俩又开始探讨内心荒凉的...

网友评论

      本文标题:2022-09-12

      本文链接:https://www.haomeiwen.com/subject/ngwqortx.html