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和标记)的忠实拥护者。 这是我提到的“前端崛起”范式的又一个生动表达。 我们已经编写了完整的教程,介绍如何使用静态网站生成器(例如Jekyll或Hugo ,甚至使用像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/

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/392926.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

leetcode145. 二叉树的后序遍历(dfs)

给定一个二叉树&#xff0c;返回它的 后序 遍历。示例:输入: [1,null,2,3] 1\2/3 输出: [3,2,1]class Solution {List<Integer> listnew ArrayList<>();public List<Integer> postorderTraversal(TreeNode root) {getPostorderTraversal(root);return list;…

[luoguP2801] 教主的魔法(二分 + 分块)

传送门 以为对于这类问题线段树都能解决&#xff0c;分块比线段树菜&#xff0c;结果培训完才知道线段树是一种特殊的分块方法&#xff0c;有的分块的题线段树不能做&#xff0c;看来分块还是有必要学的。 对于这个题&#xff0c;先分块&#xff0c;然后另开一个数组对于每个块…

鸿蒙系统适配开发,捕获科技拟建立鸿蒙开发组 为区块链钱包客户适配鸿蒙系统做筹备...

遭遇美国“实体清单”封杀的第85天&#xff0c;华为“鸿蒙”横空出世&#xff01;8月9日下午&#xff0c;在华为全球开发者大会上&#xff0c;当余承东正式宣布鸿蒙系统(Harmony OS)发布的时候&#xff0c;全场掌声雷动&#xff01;世界上第一个由中国企业自主研发的全平台微内…

[arm驱动]linux内核中断编程

第一部分获取中断(开启硬件中断)一、中断的申请注销: 1&#xff09;中断的申请 12int request_irq(unsigned int irq, irq_handler_t handler, unsigned long irqflags, const char *devname, void *dev_id) 2)中断的注销 1void free_irq(unsigned int irq, void *dev_id) 3&am…

关于VCP(Virtual Com Port)拓展的调试经历(一)

* The Overview 前日&#xff0c;接到老板部署的任务&#xff0c;将现有的基于STM32L151与L432的LoRaWAN程序中添加USB CDC(Communication Device Class)功能&#xff0c;并枚举为VCP(Virtual Com Port)用以替代以往的串口打印。很疑惑为什么以前架构代码的时候没有添加进去。。…

leetcode701. 二叉搜索树中的插入操作(dfs)

给定二叉搜索树&#xff08;BST&#xff09;的根节点和要插入树中的值&#xff0c;将值插入二叉搜索树。 返回插入后二叉搜索树的根节点。 输入数据保证&#xff0c;新值和原始二叉搜索树中的任意节点值都不同。注意&#xff0c;可能存在多种有效的插入方式&#xff0c;只要树在…

三星s6 android 8.0,再见Android 8.0,三星s6全系列系统都停止了,第一代国王已经倒下了吗?...

对于Android用户而言&#xff0c;最令人兴奋的事情是系统更新&#xff0c;因为该更新意味着更流畅的体验和更加用户友好的功能. 但是&#xff0c;旧的三星S6并不是那么幸运&#xff0c;并且不再错过Android 8.0.三星s6的全系列指的是三星s6&#xff0c;三星s6 edge&#xff0c;…

devise tree_Devise如何确保您的Rails应用密码安全

devise treeby Tiago Alves由蒂亚戈阿尔维斯(Tiago Alves) Devise如何确保您的Rails应用密码安全 (How Devise keeps your Rails app passwords safe) Devise is an incredible authentication solution for Rails with more than 40 million downloads. However, since it ab…

Exchange 2010无法安装问题解决方法

当你在活动目录(AD)森林中安装多台全局编录服务器(GC)之后,默认情况下你会发现在AD站点里面自动生成二条站点连接,从上面的截图可以看到目前在AD森林的Default-First-Site-Name(默认站点)里面有6台GC。 从上面的截图可以看到目前只有一台叫做Sh-Site1GC(全局编录服务器)是处于运…

android edittext 不滚动,EditText 设置可以垂直滑动但是不可输入

一、前言&#xff1a;android:id"id/edtInput"android:layout_width"match_parent"android:layout_height"60dp"android:background"drawable/round_theme_3_gray"android:gravity"top"android:hint"string/please_inp…

snmpd修改端口

http://blog.csdn.net/cau99/article/details/5077239 http://blog.csdn.net/gua___gua/article/details/48547701转载于:https://www.cnblogs.com/diyunpeng/p/6829592.html

leetcode LCP 19. 秋叶收藏集(dp)

小扣出去秋游&#xff0c;途中收集了一些红叶和黄叶&#xff0c;他利用这些叶子初步整理了一份秋叶收藏集 leaves&#xff0c; 字符串 leaves 仅包含小写字符 r 和 y&#xff0c; 其中字符 r 表示一片红叶&#xff0c;字符 y 表示一片黄叶。 出于美观整齐的考虑&#xff0c;小扣…

步进电机 步距角 编码器_我如何迈出了学习编码的第一步

步进电机 步距角 编码器A couple of months ago, I was chatting to a developer at work about how I’ve always wanted to learn to code but never tried.几个月前&#xff0c;我正在与一个开发人员聊天&#xff0c;讨论我一直想学习编码但从未尝试过的方法。 Coding alwa…

第五章:配置使用FastJson返回Json视图

fastJson是阿里巴巴旗下的一个开源项目之一&#xff0c;顾名思义它专门用来做快速操作Json的序列化与反序列化的组件。它是目前json解析最快的开源组件没有之一&#xff01;在这之前jaskJson是命名为快速操作json的工具&#xff0c;而当阿里巴巴的fastJson诞生后jaskjson就消声…

一加6android9玩飞车掉,解锁新速度:一加6T深度评测

解锁新速度&#xff1a;一加6T深度评测2019-11-02 14:28:595点赞2收藏4评论创作立场声明&#xff1a;我们只谈智能硬件&#xff0c;向改变生活的智能硬件Say“嗨”&#xff01;作为安卓旗舰机成员&#xff0c;一加这个品牌在玩机一类的同学手里可是大放光彩&#xff0c;各种刷机…

设计模式(第十七式:迭代器模式)

概念&#xff1a;  迭代器模式&#xff1a;Provide a way to access the elements of an aggregarte object sequentiaally with exposing its underlying representation. 提供一种访问容器对象内每个元素的一种方式&#xff0c;并且不暴露对象的一些内部细节。实现&#xf…

探讨跨域请求资源的几种方式

[转自&#xff1a;http://www.cnblogs.com/dojo-lzz/p/4265637.html] 什么是跨域JSONPproxy代理corsxdr由于浏览器同源策略&#xff0c;凡是发送请求url的协议、域名、端口三者之间任意一与当前页面地址不同即为跨域。具体可以查看下表&#xff08;来源&#xff09; JSONP 这种…

算法训练营 重编码_编码训练营适合您吗?

算法训练营 重编码by Joanna Gaudyn乔安娜高登(Joanna Gaudyn) 编码训练营适合您吗&#xff1f; (Is a Coding Bootcamp something for you?) Coding bootcamps’ popularity is growing. It sounds like a perfect idea to fast-forward your career. But is it really some…

leetcode 771. 宝石与石头(set)

给定字符串J 代表石头中宝石的类型&#xff0c;和字符串 S代表你拥有的石头。 S 中每个字符代表了一种你拥有的石头的类型&#xff0c;你想知道你拥有的石头中有多少是宝石。 J 中的字母不重复&#xff0c;J 和 S中的所有字符都是字母。字母区分大小写&#xff0c;因此"a…

用ntdsutil命令中的restore object 更新版本号

备份域控建立好后&#xff0c;备份域信息&#xff0c;用目录还 原模式&#xff0c;还原域信息&#xff0c;用ntdsutil命令&#xff0c;中的 restore ob ject 更新版本号 本文转自9pc9com博客&#xff0c;原文链接&#xff1a; http://blog.51cto.com/215363/783334 如需…