Webtask后端即服务:无服务器快速教程

查尔斯·厄勒(Charles Ouellet) (By Charles Ouellet)

The word serverless is buzzing through dozens of dev circles today.

如今, 无服务器一词正在数十个开发界中流行。

It has been for a while now.

已经有一段时间了。

I’ve been meaning to exit my code editor and come talk about the trend here. Especially since I discovered Webtask, a few months ago.

我一直想退出我的代码编辑器,然后在这里谈论趋势。 特别是自几个月前我发现Webtask以来。

So, in between bug fixes, support & new features, I finally took some time to sit down and write a little.

因此,在错误修复,支持和新功能之间,我终于花了一些时间坐下来写一点东西。

In this post, I’ll touch on serverless architectures and Backend as a Service tools a bit. But I’ll mostly focus on offering a simple yet meaningful serverless e-commerce tutorial. And I’ll use our own HTML/JS shopping cart platform & Webtask to do so.

在本文中,我将稍微介绍一下无服务器架构和后端即服务工具。 但是,我主要集中在提供一个简单而有意义的无服务器电子商务教程。 而且,我将使用我们自己HTML / JS购物车平台和Webtask来实现。

什么是无服务器架构,为什么要关心? (What is a serverless architecture, and why should you care?)

Like the “JAMstack”, serverless architecture is a new web development trend subscribing to the “rise of the frontend” paradigm we’re in. In layman’s terms, it’s a way to run server-side code in the cloud without worrying about web servers, routing, etc. It relies heavily on Backend as a Service (Baas) third parties such as Webtask, or the most popular kid on the block: AWS Lambda. With these BaaS services, you just write code and let them take care of all the underlying infrastructure. Scaling-wise, such an approach is quite awesome: the abstraction layer these services offer can handle peaks of traffic on your site wonderfully.

“ JAMstack”一样无服务器架构是一种新的Web开发趋势,它遵循了我们所处的“前端”范式。用外行的话来说,这是一种在云中运行服务器端代码而无需担心Web服务器的方法。 ,路由等。它在很大程度上依赖于后端即服务(Baas)第三方,例如Webtask或该区块中最受欢迎的孩子: AWS Lambda 。 使用这些BaaS服务,您只需编写代码,并让它们处理所有底层基础结构。 在扩展方面,这种方法非常出色:这些服务提供的抽象层可以出色地处理您网站上的流量高峰。

As you may know, we’re big fans of the JAMstack (JavaScript, APIs & Markup) here at Snipcart. It’s another vibrant expression of the “rise of the frontend” paradigm I mentioned. We’ve written whole tutorials on how to run e-commerce with static site generators such as Jekyll or Hugo, and even with API-first CMS like Contentful. From cost to tech stacks shifts, I believe such an approach will deeply impact how businesses handle web development in the next years.

如您所知,我们是Snipcart的JAMstack (JavaScript,API和标记)的忠实拥护者。 这是我提到的“前端崛起”范式的又一个生动表达。 我们已经编写了完整的教程,介绍如何使用静态网站生成器(例如JekyllHugo ,甚至使用像Contentful这样的API优先CMS)来运行电子商务。 从成本到技术堆栈的转变,我相信这种方法将在未来几年深刻影响企业处理Web开发的方式。

However, I’m aware that it has its limits: a modern static site is raw content, which means using dynamic features such as webhooks would be impossible without some server-side code. That’s where Webtask comes in.

但是,我知道它有其局限性:现代的静态网站是原始内容 ,这意味着如果没有一些服务器端代码,就不可能使用诸如webhooks之类的动态功能。 这就是Webtask出现的地方。

Webtask:目标任务(或FaaS)的后端即服务 (Webtask: Backend-as-as-Service for Targeted Tasks (or FaaS))

Webtask is a neat service crafted by Auth0, the good folks who made a serious dent in the online authentication world. Acting as a Function as a Service, it basically removes the need to configure a backend for simple mobile or single-page apps. Often compared to AWS Lambda, it allows developers to write server-side logic & functions executed via HTTP calls. So it’s one of the best Backend as a Service tools out there for developers who’d rather focus on the frontend than configure the backend.

Webtask是Auth0精心制作的一项精美服务, Auth0是在在线身份验证世界中大受打击的好伙伴 。 作为功​​能即服务,它基本上消除了为简单的移动或单页面应用程序配置后端的需要。 与AWS Lambda相比 ,它通常使开发人员可以编写通过HTTP调用执行的服务器端逻辑和功能。 因此,对于那些宁愿专注于前端而不是配置后端的开发人员来说,它是最好的后端即服务工具之一。

Now let’s see how perfect it is for the use case we’ll explore in this serverless tutorial.

现在,让我们看看在本无服务器教程中将探讨的用例有多完美。

无服务器电子商务教程:webhooks和自定义运费 (Serverless e-commerce tutorial: webhooks & custom shipping rates)

At Snipcart, I believe one of our most powerful features is the Webhooks Shipping API. Simply put, it gives you full control on how your e-commerce site handles shipping.

在Snipcart,我相信我们最强大的功能之一就是Webhooks Shipping API 。 简而言之,它使您可以完全控制电子商务网站如何处理运输。

However, leveraging this feature requires running server-side code. So if you wanted to use a JAMstack set up with a static site generator, you’d be screwed. Thanks to Webtask, however, you’re not! In this serverless tutorial, we’ll use it to host the e-commerce shipping function we need directly via their platform.

但是,利用此功能需要运行服务器端代码。 因此,如果您想使用带有静态站点生成器的JAMstack设置,那将会很麻烦。 幸亏有了Webtask,您不是! 在本无服务器教程中,我们将使用它直接通过其平台托管我们需要的电子商务运送功能。

我们简单的无服务器电子商务用例 (Our simple serverless e-commerce use case)

Now, let’s pretend we have a static e-commerce site running with Snipcart.

现在,让我们假设我们有一个与Snipcart一起运行的静态电子商务网站。

And let’s say we want to offer three special shipping rates:

假设我们要提供三种特殊的运费:

  • One for customers in our Québec hometown

    在魁北克故乡为客户提供的一种
  • One for US customers

    一个给美国客户
  • One for all other international customers

    一个供所有其他国际客户使用

1.如何创建Webtask功能 (1. How to create the Webtask function)

First of all, let me explain a little how our shipping API works. Snipcart sends all the order details to a URL you can specify in your merchant dashboard. Using this data, you can then write code to return available shipping rates to your end customers.

首先,让我解释一下我们的运输API如何工作。 Snipcart将所有订单详细信息发送到您可以在商家信息中心中指定的URL。 然后,使用这些数据,您可以编写代码以将可用的运费退还给最终客户。

Start by creating an account on https://webtask.io/. Once it’s done, follow their steps to install the Webtask CLI via npm.

首先在 https://webtask.io/ 上创建一个帐户 完成后,请按照他们的步骤通过 npm 安装Webtask CLI

We’ll now create a file named shipping_task.js. It'll contain all the code needed to parse the order details received from Snipcart and return the available shipping rates.

现在,我们将创建一个名为shipping_task.js的文件。 它包含解析从Snipcart收到的订单详细信息并返回可用运费的所有代码。

Let’s start by exporting a module that Webtask will understand.

让我们从导出Webtask可以理解的模块开始。

module.exports = function (context, cb) {
    cb(null, context.body);
}

The first parameter, context, contains the data Snipcart will send to your application. Webtask takes care of parsing the JSON, and you can access all the event details along with the order via context.body.

第一个参数context是包含Snipcart将发送到您的应用程序的数据。 Webtask负责解析JSON,您可以通过context.body访问所有事件详细信息以及顺序。

With the code above, our task would return the request body that it received; pretty useless. ;)

使用上面的代码,我们的任务将返回它收到的请求正文; 真没用。 ;)

Now let’s say we want to offer free shipping for customers in Québec.

现在,我们要为魁北克的客户提供免费送货。

module.exports = function (context, cb) {
    var orderDetails = context.body.content;
    var rates = [];
    
    var address = orderDetails.shippingAddress || order.billingAddress;
    
    if (address.country == "CA" && address.province == "QC") {
      rates.push({
        cost: 0,
        description: "Free shipping for Québec residents!"
      });
    }
    
    cb(null, { rates: rates });
}

Ain’t that nice? However, with this code, customers outside Québec won’t have any shipping options. So we’ll make sure to return a standard shipping rate in case the order does not match our conditions:

那不是很好吗? 但是,使用此代码,魁北克省以外的客户将没有任何运送选择。 因此,如果订单不符合我们的条件,我们将确保返回标准的运费:

if (rates.length === 0) {
  rates.push({
    cost: 20,
    description: "Standard shipping"
  });  
}

You can see below the complete code with some additional conditions:

您可以在完整的代码下方看到一些附加条件:

module.exports = function (context, cb) {
    console.log(context.body);

    var orderDetails = context.body.content;

    var rates = [];

    var address = orderDetails.shippingAddress || order.billingAddress;

    if (address.country == "CA" && address.province == "QC") {
      rates.push({
        cost: 0,
        description: "Free shipping for Québec residents!"
      });
    }

    if (address.country == "CA" && address.province != "QC") {
      rates.push({
        cost: 10,
        description: "Shipping to Canada"
      });
    }

    if (address.country == "US") {
      rates.push({
        cost: 15,
        description: "Shipping to US"
      });
    }

    if (rates.length === 0) {
      rates.push({
        cost: 20,
        description: "Standard shipping"
      });
    }

    cb(null, { rates: rates });
}

Webtask will then generate a URL; you should see it in your terminal.

然后,Webtask将生成一个URL。 您应该在终端中看到它。

Simply use this URL and when configuring the Webhooks Shipping API.

在配置Webhooks运送API时,只需使用此URL。

2.保护无服务器组件 (2. Securing the serverless component)

With our current set up, anyone could send requests to this API, right? That’s not something we want. So we’ll make sure that the function only handles requests coming from Snipcart. We’ll use our request validation API to do so.

通过我们当前的设置,任何人都可以向该API发送请求,对吗? 那不是我们想要的东西。 因此,我们将确保该函数仅处理来自Snipcart的请求。 我们将使用请求验证API来执行此操作。

First, we’ll need to send a Snipcart secret API key to the task in order to call the request validation API. We don’t want to expose it directly through the code, so we’re going to use the secrets feature that Webtask has. It allows us to pass secret parameters to the task that will be encrypted and accessible via the context object.

首先,我们需要向任务发送Snipcart秘密API密钥,以调用请求验证API。 我们不想直接通过代码公开它,因此我们将使用Webtask具有的secrets功能。 它允许我们将秘密参数传递给将被加密并可以通过context对象访问的任务。

When creating the task, I added the --secret switch:

创建任务时,我添加了--secret开关:

wt create shipping_task.js — secret snipcartApiKey=MY_SECRET_API_KEY

You will then be able to access this value using context.secrets.snipcartApiKey. We'll also use the request module, so we'll need to require it at the beginning of the file:

然后,您将可以使用context.secrets.snipcartApiKey访问此值。 我们还将使用request模块,因此我们需要在文件开头要求它:

var request = require('request');

When we make requests to your Webhooks, we always include a request token in the request headers. The header is named X-Snipcart-RequestToken. We'll access it through our context object again:

当我们向您的Webhooks发出请求时,我们总是在请求标头中包含一个请求令牌。 标头名为X-Snipcart-RequestToken 。 我们将再次通过context对象访问它:

var requestToken = context.headers['x-snipcart-requesttoken'];

Please note that all the headers are in lower cases with Webtask.

请注意,Webtask的所有标头均小写。

Here are the options we’ll use to send the request to our API:

以下是我们用于将请求发送到我们的API的选项:

var requestToken = context.headers['x-snipcart-requesttoken'];
var secretApiKey = context.secrets.snipcartApiKey;

var requestOptions = {
  url: 'https://app.snipcart.com/api/requestvalidation/' + requestToken,
  headers: {
    "Accept": "application/json"
  },
  auth: {
    user: secretApiKey
  }
};

We’ll run this request and only execute the code in the callback if it’s successful.

我们将运行此请求,仅在成功的情况下在回调中执行代码。

request(requestOptions, function(error, response, body) {
  if (response.statusCode === 200) {
      // Return rates
  } else {
    // Return an error when the request does not come from Snipcart.    
    cb("Only Snipcart can call this code!");
  }
});

So my whole function now looks like this:

所以我的整个函数现在看起来像这样:

var request = require('request');

module.exports = function (context, cb) {
  var requestToken = context.headers['x-snipcart-requesttoken'];
  var secretApiKey = context.secrets.snipcartApiKey;

  var requestOptions = {
    url: 'https://app.snipcart.com/api/requestvalidation/' + requestToken,
    headers: {
      "Accept": "application/json"
    },
    auth: {
      user: secretApiKey
    }
  };

  request(requestOptions, function(error, response, body) {
    if (response.statusCode === 200) {
      var orderDetails = context.body.content;
      var rates = [];

      var address = orderDetails.shippingAddress || order.billingAddress;

      if (address.country == "CA" && address.province == "QC") {
        rates.push({
          cost: 0,
          description: "Free shipping for Québec residents!"
        });
      }

      if (address.country == "CA" && address.province != "QC") {
        rates.push({
          cost: 10,
          description: "Shipping to Canada"
        });
      }

      if (address.country == "US") {
        rates.push({
          cost: 15,
          description: "Shipping to US"
        });
      }

      if (rates.length === 0) {
        rates.push({
          cost: 20,
          description: "Standard shipping"
        });
      }

      cb(null, { rates: rates });
    }
    else {
      cb("Only Snipcart can call this code!");
    }
  });
}
Webtask结束语和无服务器方法 (Closing words on Webtask & the serverless approach)

Coming up with this little Webtask function for a static site running Snipcart took me less than two hours. Of course, we could’ve focused on other e-commerce functions: handling webhooks to make the bridge between Snipcart and external accounting systems, automating digital goods delivery, and more.

对于运行Snipcart的静态网站,想出了这个小的Webtask功能,花了我不到两个小时的时间。 当然,我们本可以专注于其他电子商务功能:处理Webhooks以在Snipcart和外部会计系统之间架起桥梁,实现数字商品交付的自动化等。

I really believe there are tons of exciting serverless use cases developers should try to handle with Auth0’s Webtask. Any integration with an API, or delegating more long-running/CPU-consuming jobs would make much sense!

我真的相信开发人员应该尝试使用Auth0的Webtask处理大量令人兴奋的无服务器用例。 与API进行任何集成,或委派更多长时间运行/占用CPU的作业都非常有意义!

The serverless approach is gearing up to have quite an impact on our work as developers. As we’re now seeing with RESTful APIs, many services will start relying on functions developed or hosted by others. The near future will bring more and more microservices hosted in environments like Webtask & AWS Lambda. Especially coupled with the rise of frameworks like Vue & the JAMstack.

无服务器方法正在加速发展,对我们作为开发人员的工作产生很大影响。 正如我们现在使用RESTful API所看到的那样,许多服务将开始依赖于其他人开发或托管的功能。 在不久的将来,将在Webtask和AWS Lambda等环境中托管越来越多的微服务。 特别是随着Vue和JAMstack等框架的兴起。

So I sincerely hope this post inspires developers to leverage the FaaS power of Webtask on different serverless projects, e-commerce or not. And of course, I’d be more than interested to have a look at such set ups. You can shoot us an email at geeks@snipcart.com if you got something similar to share, or if you have questions regarding this approach!

因此,我衷心希望这篇文章能激发开发人员在不同的无服务器项目(无论是否为电子商务)中利用Webtask的FaaS功能。 当然,我对研究这样的设置非常感兴趣。 如果您有类似的分享内容,或者对这种方法有疑问,可以通过geeks@snipcart.com向我们发送电子邮件。

Liked the post? Take a second to ? and share it on Twitter!

喜欢这个职位吗? 花一秒钟来? 并在Twitter上分享

Originally published on the Snipcart blog and in our newsletter.

最初发布在 Snipcart博客 我们的时事通讯中

翻译自: https://www.freecodecamp.org/news/webtask-backend-as-a-service-quick-serverless-tutorial/

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值