使用Webtask.io构建无服务器MERN Story应用程序-部署零:1

Being a fullstack developer is fun to me and a lot of us enjoy the role because it's more challenging. We have the opportunity as fullstack developers to play with every possible tool on the web and make something reasonable out of it.

成为一名全职开发人员对我来说很有趣,我们很多人都喜欢这个角色,因为它更具挑战性。 作为全栈开发人员,我们有机会使用网络上所有可能的工具,并从中做出合理的选择。

Unfortunately some engineers are not fortunate enough to be in an environment that allow them showcase their fullstack powers. Either they are spitting Laravel blade template and rolling out APIs as backend developers or struggling with CSS Flexbox and React as frontend developers.

不幸的是,有些工程师还不够幸运,无法在这样的环境中展示自己的全能。 他们要么分散Laravel刀片模板,然后将API作为后端开发人员推出,要么与CSS Flexbox和React作为前端开发人员进行斗争。

The pressure is more on frontend engineers because backend engineers can afford to have a good UI without being frontend masters. Frontend engineers just need to know a lot about their server language and even the server configuration to survive.

前端工程师承受的压力更大,因为后端工程师可以负担得起良好的UI而无需成为前端大师。 前端工程师只需要了解很多有关他们的服务器语言,甚至是服务器配置的知识即可生存。

Serverless technology is starting the put back smiles on our faces as frontend engineers. Now we can focus on the browser and rollout servers within 3 minutes.

无服务器技术开始让前端工程师回味无穷。 现在,我们可以在3分钟内专注于浏览器和部署服务器。

我们的任务 ( Our Task )

The image above shows what we intend to build. It's a full functional app written in React and backed by Node, Express and Mongo DB. The backend is "Serverless" with Webtask and composed of just functions and simple Express routes.

无服务器概念 ( Serverless Concept )

"Server-less" is a coined term that refers to building web apps without bothering about how the server is set up. The term causes confusion to developers that are new to the concept. It doesn't mean that your app won't live on a server, rather it means that the sever setup and management is left out to be managed by the provisioning platform.

“无服务器”是一个专有名词,指的是构建Web应用程序而不必担心服务器的设置方式。 该术语使对于该概念不熟悉的开发人员感到困惑。 这并不意味着您的应用程序将无法在服务器上运行,而是意味着服务器的设置和管理将由配置平台进行管理。

One other thing you might hear when "server-less" is discussed is Function as a Service (FaaS). Serverless technique is simplified by functions. As a developer, you end up writing and deploying compassable functions. This concept will become clearer when we start getting our hands dirty.

讨论“无服务器”时,您可能会听到的另一件事是功能即服务(FaaS)。 无服务器技术通过功能得以简化。 作为开发人员,您最终要编写和部署可指南功能。 当我们开始弄脏双手时,这个概念将变得更加清晰。

网络任务 ( Webtask )

Google Cloud Functions, stdlib, Azure Cloud Functions, AWS Lambda, etc are all serverless platforms you can lay your hands. The smart guys at Auth0 introduced
Webtask which is yet another serverless platform which is seamlessly easy to get started with.

Webtask ,这是另一个无服务器平台,可以轻松上手。

Webtask is used internal by the Auth0 team to manage and run their platform user custom codes. They were generous enough to make this available to the public so we can go ahead and build apps with it. My choice for Webtask is greatly influenced my how easy it is to get started with less overwhelming docs.

Auth0团队在内部使用Webtask来管理和运行其平台用户自定义代码。 他们足够慷慨地向公众提供此功能,因此我们可以继续使用它构建应用程序。 我对Webtask的选择极大地影响了我使用不那么繁琐的文档入门的难易程度。

建立项目 ( Setting Up Project )

Our project is split into two -- the webtask backend API and a React driven frontend. Let's take care of Webtast setup first, then setup the frontend when it's time to build that.

我们的项目分为两个部分-webtask后端API和React驱动的前端。 让我们先处理Webtast的设置,然后在需要构建前端时进行设置。

Webtask just as you might have guessed, provides a CLI tool to make deploying you functions easy. First thing to do is install this CLI tool:

就像您可能已经猜到的那样,Webtask提供了一个CLI工具,可简化您的功能部署。 首先要做的是安装此CLI工具:

npm install -g wt-cli

To deploy functions, Webtask needs a way to identify you and your functions. Therefore, an account is needed. Head straight to the Webtask website and login. You will use your email to login to the CLI.

要部署功能,Webtask需要一种识别您和您的功能的方法。 因此,需要一个帐户。 直接前往Webtask网站并登录 。 您将使用您的电子邮件登录到CLI。

Run the following command to login via your CLI:

运行以下命令以通过CLI登录:

wt init<YOUR-EMAIL>

Create your project directory anywhere on your machine, add an index.jsin the directory with the following content:

在机器上任何位置创建项目目录,在目录中添加具有以下内容的index.js

module.exports = function (cb) {
  cb(null, 'Hello World');
}

Hit the URL logged in the console after running the following command on the directory to see your deployed app:

在目录上运行以下命令后,单击控制台中记录的URL,以查看已部署的应用程序:

wt create index

I was amazed too!

我也很惊讶!

Now that we have seen a basic example, let's build something serious and interesting -- an API for our Stories app.

现在,我们已经看到了一个基本示例,让我们构建一些严肃而有趣的东西-Stories应用程序的API。

API项目结构 (API Project Structure)

|---middlwares
|------db.js
|---models
|------Story.js
|---routes
|------stories.js
|---package.json
|---index.js

The pacakge.json contains the dependencies for this project as well as important scripts to run and bundle our project to be Webtask-ready:

pacakge.json包含此项目的依赖项以及运行和捆绑我们的项目以支持Webtask的重要脚本:

{
  "name": "wt-mern-api",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "npm run create -- --watch",
    "create": "wt create index --bundle"
  },
  "author": "",
  "license": "MIT",
  "dependencies": {
    "body-parser": "^1.17.1",
    "express": "^4.15.2",
    "mongoose": "^4.9.5",
    "webtask-tools": "^3.2.0"
  }
}

Webtask编程模型和Express ( Webtask Programming Model & Express )

Webtask integrates best JavaScript. As you have seen, we just exported a function and an app was created. You might be wondering how you could bring in a different programming model to the scene.

Webtask集成了最佳JavaScript。 如您所见,我们只是导出了一个函数,然后创建了一个应用程序。 您可能想知道如何将不同的编程模型引入现场。

Exporting functions is just one of the programming models supported by Webtask. It happens to be the most basic but that not withstanding, you can employ what works for you. In our case we want to use Express.

导出功能只是Webtask支持的编程模型之一。 它碰巧是最基本的,但并非经久不衰,您可以采用适合自己的方法。 在本例中,我们要使用Express。

Webtask has a utility tool, webtask-tools, to help you bind your express app to a Webtask context. Therefore, rather than exporting a simple function, you can export an express app bound to Webtask using webtask-tools:

Webtask有一个实用工具webtask-tools ,可帮助您将快速应用程序绑定到Webtask上下文。 因此,您无需导出简单的功能,而可以使用webtask-tools导出绑定到Webtask的快速应用程序:

// ./index.js
var Express = require('express');
var Webtask = require('webtask-tools');
var bodyParser = require('body-parser')
var app = Express();

app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

// yet to be created
app.use(require('./middlewares/db').connectDisconnect);
require('./routes/stories')(app);

module.exports = Webtask.fromExpress(app);

If you are familiar with Express, you will see a lot of familiar codes. The big change is that rather than listening, we are exporting a function created from the Express app using webtask-tools.

如果您熟悉Express,将会看到很多熟悉的代码。 最大的变化是,我们正在使用webtask-tools导出从Express应用创建的功能,而不是监听。

The following lines are yet to be created but the handle database connection/disconnection and routes respectively:

以下各行尚未创建,但分别处理数据库连接/断开连接和路由:

...
app.use(require('./middlewares/db').connectDisconnect);
require('./routes/stories')(app);
...

数据库,连接,架构和模型 ( Database, Connection, Schema and Model )

We are trying as much as possible to be practical enough so you can have a 360 view of how useful Webtask can be. One of such practical situations is using an actual database rather than using a JSON temp file.

我们正在尝试尽可能地实用,以便您可以360度了解Webtask的实用性。 这种实际情况之一是使用实际数据库而不是使用JSON临时文件。

Mongolab数据库 (Mongolab Database)

Mongolab by Object Labs is a good choice for cloud database because they eliminate the challenges of knowing how to setup a Cloud DB by just giving you a URL after choosing where you want your database to be hosted. To get started:

Object Labs的Mongolab是云数据库的不错选择,因为它们消除了知道如何设置Cloud DB的难题,只需在选择要托管数据库的位置后为您提供一个URL。 开始:

  • Quickly Sign up.

    快速注册
  • Create a database. A database URL will be supplied on the dashboard, copy and keep safe.

    创建一个数据库 。 数据库URL将提供在仪表板上,并进行复制并保持安全。
  • Create a user to authenticate the database. You can do this by clicking on the just created database, selecting the Users' tab and clicking Add database user.

    创建一个用户来认证数据库。 您可以通过单击刚刚创建的数据库,选择“用户”选项卡,然后单击“ 添加数据库用户 ”来执行此操作

猫鼬图式 ( Mongoose Schema )

Mongoose is a library that makes interacting with Mongo DB easier. It provides a more friendly API for connecting, creating, updating and querying your database. To do this, it uses a schemas to map Mongo collections and their properties to JavaScript object.

Mongoose是一个使与Mongo DB交互更容易的库。 它提供了一个更友好的API,用于连接,创建,更新和查询数据库。 为此,它使用模式将Mongo集合及其属性映射到JavaScript对象。

// ./models/Story.js
const mongoose = require('mongoose');

module.exports = new mongoose.Schema({
    author: String,
    content: String,
    created_at: Date,
    id: mongoose.Schema.ObjectId
})

连接和型号 (Connection and Model)

Next is to connect to a database and disconnect at the beginning and end of each request. To set this up, we need to use a middleware which will execute before each of our Express routes:

接下来是连接到数据库,并在每个请求的开始和结束时断开连接。 要进行设置,我们需要使用一个中间件,该中间件将在我们的每个Express路由之前执行:

// ./middlewares/db.js
var mongoose = require('mongoose');
// import Story schema
const StorySchema = require('../models/Story')

module.exports = {
    // Connect/Disconnect middleware
    connectDisconnect: (req, res, next) => {
        // Create connection using Mongo Lab URL
        // available in Webtask context
        const connection = mongoose.createConnection(req.webtaskContext.secrets.MONGO_URL);
        // Create a mongoose model using the Schema
        req.storyModel = connection.model('Story', StorySchema);
        req.on('end', () => {
            // Disconnect when request
            // processing is completed
            mongoose.connection.close();
        })
        // Call next to move to
        // the next Express middleware
        next()
    },
}

This middleware handles both connecting and disconnecting to a Mongolab database. The connection is achieved by passing a connection URL to the createConnection method. The URL is received via Webtask context; see next title.

该中间件处理与Mongolab数据库的连接和断开连接。 通过将连接URL传递到createConnection方法来实现连接。 URL是通过Webtask上下文接收的; 参见下一个标题。

When we establish a connection, we create a Mongoose model and attach the model to our request object.

建立连接后,我们将创建一个Mongoose模型并将该模型附加到我们的请求对象。

We then attach an event listener to close the connection at the end of the request. next is called to pass down and continue with whatever middleware is next in the stack. This will most likely be an Express route.

然后,我们附加一个事件侦听器,以在请求结束时关闭连接。 调用next传递并继续使用堆栈中的下一个中间件。 这很可能是Express路线。

Web任务上下文 (Webtask Context)

You can access contextual information via the Webtask context object. Such information can be used to store sensitive credentials like secrets, dynamic details like query strings, etc.

您可以通过Webtask上下文对象访问上下文信息。 此类信息可用于存储敏感信息(例如机密信息),动态详细信息(例如查询字符串)等。

You can access the context via the function parameter:

您可以通过function参数访问上下文:

module.exports = function(context, cb) {
    cb(null, { hello: context.data.name || 'Anonymous' });
}   

When using Express, you can access it from req.webtaskContext just like we saw in the database connection example. The MONGO_URL secret is passed in via the terminal while running the app:

使用Express时,可以从req.webtaskContext访问它,就像在数据库连接示例中看到的那样。 MONGO_URL秘密在运行应用程序时通过终端传递:

wt create index --secret MONGO_URL=<MONGOLAB-CONNECTION-URL> --bundle

快速CRUD路线 ( Express CRUD Routes )

We have written all the helper codes our routes need to function. Tackling these routes is the next task:

我们已经编写了路线所需的所有辅助代码。 解决这些路线是下一个任务:

// ./routes/stories.js
var mongoose = require('mongoose');

const Story = require('../models/Story');

module.exports = (app) => {
  app.get('/stories', (req, res) => {
      req.storyModel.find({}).sort({'created_at': -1}).exec((err, stories) => res.json(stories))
  });

  app.post('/stories', (req, res) => {
      const newStory = new req.storyModel(Object.assign({}, req.body, {created_at: Date.now()}));
      newStory.save((err, savedStory) => {
          res.json(savedStory)
      })
  })

  app.put('/stories', (req, res) => {
    const idParam = req.webtaskContext.query.id;
    req.storyModel.findOne({_id: idParam}, (err, storyToUpdate) => {
        const updatedStory = Object.assign(storyToUpdate, req.body);
        updatedStory.save((err, story) => res.json(story))
    })
  })

  app.delete('/stories', (req, res) => {
    const idParam = req.webtaskContext.query.id;
    req.storyModel.remove({_id: idParam}, (err, removedStory) => res.json(removedStory));
  })
}
  • GET: /stories route uses mongoose to fetch all the stories stored in the database and sort them by date created in descending order

    GET: /stories route使用猫鼬来获取存储在数据库中的所有故事,并按降序创建的日期对它们进行排序
  • POST: /stories is used to create a new story by storing the payload on req.body

    POST: /stories用于通过将有效负载存储在req.body来创建新故事
  • PUT: /stories expects an id query string which it uses to find a story and updates the story based on the id

    PUT: /stories需要一个id查询字符串,用于查找故事并根据该id更新故事
  • DELETE: /stories just like PUT, expects an id as well and removes an entry from the database collection based on the id

    DELETE: /stories与PUT一样,也需要一个id ,并根据该id从数据库集合中删除一个条目

最后的话 ( Final Words )

You can hit the following URL using GET in Postman to see a response of an array if stories:

您可以在Postman中使用GET命中以下URL,以查看故事的数组响应:

https://wt-nwambachristian-gmail_com-0.run.webtask.io/wt-mern-api/stories

Remember to run the app one more time if you have not been doing so to deploy your functions:

如果尚未部署应用程序,请记住再运行一次该应用程序:

wt create index --secret MONGO_URL=<MONGOLAB-CONNECTION-URL> --bundle

The next part of this article will describe how we will consume these endpoints in a React app so as to have a full application. We will also deploy the React app so has to have everything running on a remote server.

本文的下一部分将描述我们如何在React应用程序中使用这些终结点,以便拥有完整的应用程序。 我们还将部署React应用程序,因此必须使所有内容都在远程服务器上运行。

翻译自: https://scotch.io/tutorials/build-a-serverless-mern-story-app-with-webtask-io-zero-to-deploy-1

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值