1634888562
Trong những ngày đầu của Web, các trang web chủ yếu bao gồm HTML và CSS . Nếu bất kỳ JavaScript nào được tải vào một trang, nó thường ở dạng các đoạn mã nhỏ cung cấp các hiệu ứng và tính tương tác. Do đó, các chương trình JavaScript thường được viết hoàn toàn trong một tệp và được tải vào một script
thẻ. Một nhà phát triển có thể chia JavaScript thành nhiều tệp, nhưng tất cả các biến và hàm vẫn sẽ được thêm vào phạm vi toàn cầu .
Nhưng khi các trang web phát triển với sự ra đời của các khung công tác như Angular , React và Vue , và với các công ty tạo ra các ứng dụng web nâng cao thay vì các ứng dụng máy tính để bàn, JavaScript hiện đóng một vai trò quan trọng trong trình duyệt. Do đó, nhu cầu sử dụng mã của bên thứ ba cho các tác vụ phổ biến hơn nhiều, để chia nhỏ mã thành các tệp mô-đun và tránh làm ô nhiễm không gian tên chung.
Đặc tả ECMAScript 2015 đã giới thiệu các mô-đun cho ngôn ngữ JavaScript, cho phép sử dụng các câu lệnh import
và export
. Trong hướng dẫn này, bạn sẽ tìm hiểu mô-đun JavaScript là gì và cách sử dụng import
và export
tổ chức mã của bạn.
Trước khi khái niệm mô-đun xuất hiện trong JavaScript, khi một nhà phát triển muốn tổ chức mã của họ thành các phân đoạn, họ sẽ tạo nhiều tệp và liên kết đến chúng dưới dạng các tập lệnh riêng biệt. Để chứng minh điều này, hãy tạo một index.html
tệp mẫu và hai tệp JavaScript, functions.js
và script.js
.
Các index.html
tập tin sẽ hiển thị Tóm lại, sự khác biệt, sản phẩm và thương của hai số, và liên kết với hai tập tin JavaScript trong script
thẻ. Mở index.html
trong trình soạn thảo văn bản và thêm mã sau:
Các index.html
tập tin sẽ hiển thị Tóm lại, sự khác biệt, sản phẩm và thương của hai số, và liên kết với hai tập tin JavaScript trong script
thẻ. Mở index.html
trong trình soạn thảo văn bản và thêm mã sau:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>JavaScript Modules</title>
</head>
<body>
<h1>Answers</h1>
<h2><strong id="x"></strong> and <strong id="y"></strong></h2>
<h3>Addition</h3>
<p id="addition"></p>
<h3>Subtraction</h3>
<p id="subtraction"></p>
<h3>Multiplication</h3>
<p id="multiplication"></p>
<h3>Division</h3>
<p id="division"></p>
<script src="functions.js"></script>
<script src="script.js"></script>
</body>
</html>
HTML này sẽ hiển thị giá trị của các biến x
và y
trong h2
tiêu đề, và giá trị của các phép toán trên các biến đó trong các p
phần tử sau . Các id
thuộc tính của các phần tử được đặt cho thao tác DOM , điều này sẽ xảy ra trong script.js
tệp; tệp này cũng sẽ đặt các giá trị của x
và y
. Để biết thêm thông tin về HTML, hãy xem loạt bài Cách tạo trang web bằng HTML của chúng tôi .
Các functions.js
tập tin sẽ chứa các hàm toán học sẽ được sử dụng trong kịch bản thứ hai. Mở functions.js
tệp và thêm thông tin sau:
function sum(x, y) {
return x + y
}
function difference(x, y) {
return x - y
}
function product(x, y) {
return x * y
}
function quotient(x, y) {
return x / y
}
Cuối cùng, script.js
tệp sẽ xác định các giá trị của x
và y
, áp dụng các chức năng cho chúng và hiển thị kết quả:
const x = 10
const y = 5
document.getElementById('x').textContent = x
document.getElementById('y').textContent = y
document.getElementById('addition').textContent = sum(x, y)
document.getElementById('subtraction').textContent = difference(x, y)
document.getElementById('multiplication').textContent = product(x, y)
document.getElementById('division').textContent = quotient(x, y)
Sau khi thiết lập và lưu các tệp này, bạn có thể mở index.html
trong trình duyệt để hiển thị trang web của mình với tất cả các kết quả:
Đối với các trang web có một vài tập lệnh nhỏ, đây là một cách hiệu quả để phân chia mã. Tuy nhiên, có một số vấn đề liên quan đến cách tiếp cận này, bao gồm:
sum
, difference
vv-bây giờ tồn tại trên window
đối tượng. Nếu bạn đã cố gắng sử dụng một biến khác được gọi sum
trong một tệp khác, sẽ rất khó để biết giá trị nào sẽ được sử dụng tại bất kỳ thời điểm nào trong các tập lệnh, vì tất cả chúng sẽ sử dụng cùng một window.sum
biến. Cách duy nhất một biến có thể là riêng tư là đặt nó trong một phạm vi hàm. Thậm chí có thể có xung đột giữa một id
trong DOM có tên x
và var x
.<script>
trong trang trình duyệt.Trước khi ES6 thêm các mô-đun gốc vào ngôn ngữ JavaScript, cộng đồng đã cố gắng đưa ra một số giải pháp. Các giải pháp đầu tiên được viết bằng JavaScript vani, chẳng hạn như viết tất cả mã trong các đối tượng hoặc ngay lập tức được gọi ra các biểu thức hàm (IIFE) và đặt chúng trên một đối tượng duy nhất trong không gian tên chung. Đây là một cải tiến đối với phương pháp tiếp cận nhiều tập lệnh, nhưng vẫn có những vấn đề tương tự khi đặt ít nhất một đối tượng vào không gian tên chung và không làm cho vấn đề chia sẻ mã nhất quán giữa các bên thứ ba trở nên dễ dàng hơn.
Sau đó, một số giải pháp mô-đun đã xuất hiện: CommonJS , một cách tiếp cận đồng bộ đã được triển khai trong Node.js , Định nghĩa mô-đun không đồng bộ (AMD) , là một cách tiếp cận không đồng bộ và Định nghĩa mô-đun chung (UMD) , được dự định là một cách tiếp cận đã hỗ trợ cả hai kiểu trước đó.
Sự ra đời của các giải pháp này đã giúp các nhà phát triển dễ dàng chia sẻ và sử dụng lại mã dưới dạng các gói , mô-đun có thể được phân phối và chia sẻ, chẳng hạn như các mô-đun được tìm thấy trên npm . Tuy nhiên, vì có nhiều giải pháp và không có giải pháp nào là gốc của JavaScript, nên các công cụ như Babel , Webpack hoặc Browserify phải được triển khai để sử dụng các mô-đun trong trình duyệt.
Do có nhiều vấn đề với cách tiếp cận nhiều tệp và sự phức tạp của các giải pháp được đề xuất, các nhà phát triển đã quan tâm đến việc đưa cách tiếp cận lập trình mô-đun vào ngôn ngữ JavaScript. Do đó, ECMAScript 2015 hỗ trợ việc sử dụng các mô-đun JavaScript.
Một mô-đun là một gói các mã mà đóng vai trò như một giao diện để cung cấp chức năng cho các module khác để sử dụng, cũng như việc có thể dựa vào các chức năng của các module khác. Một mô-đun xuất để cung cấp mã và nhập để sử dụng mã khác. Các mô-đun rất hữu ích vì chúng cho phép các nhà phát triển sử dụng lại mã, chúng cung cấp một giao diện ổn định, nhất quán mà nhiều nhà phát triển có thể sử dụng và chúng không gây ô nhiễm không gian tên toàn cầu.
Các mô-đun (đôi khi được gọi là mô-đun ECMAScript hoặc Mô-đun ES) hiện có sẵn trong JavaScript và trong phần còn lại của hướng dẫn này, bạn sẽ khám phá cách sử dụng và triển khai chúng trong mã của mình.
Các mô-đun trong JavaScript sử dụng import
và export
từ khóa:
import
: Dùng để đọc mã được xuất từ mô-đun khác.export
: Được sử dụng để cung cấp mã cho các mô-đun khác.Để trình bày cách sử dụng, hãy cập nhật functions.js
tệp của bạn thành một mô-đun và xuất các chức năng. Bạn sẽ thêm export
vào trước mỗi chức năng, điều này sẽ làm cho chúng có sẵn cho bất kỳ mô-đun nào khác.
Thêm mã được đánh dấu sau vào tệp của bạn:
export function sum(x, y) {
return x + y
}
export function difference(x, y) {
return x - y
}
export function product(x, y) {
return x * y
}
export function quotient(x, y) {
return x / y
}
Bây giờ, trong script.js
, bạn sẽ sử dụng import
để lấy mã từ functions.js
mô-đun ở đầu tệp.
Lưu ý : import
phải luôn ở đầu tệp trước bất kỳ mã nào khác và cũng cần phải bao gồm đường dẫn tương đối ( ./
trong trường hợp này).
Thêm mã được đánh dấu sau vào script.js
:
import { sum, difference, product, quotient } from './functions.js'
const x = 10
const y = 5
document.getElementById('x').textContent = x
document.getElementById('y').textContent = y
document.getElementById('addition').textContent = sum(x, y)
document.getElementById('subtraction').textContent = difference(x, y)
document.getElementById('multiplication').textContent = product(x, y)
document.getElementById('division').textContent = quotient(x, y)
Lưu ý rằng các hàm riêng lẻ được nhập bằng cách đặt tên chúng trong dấu ngoặc nhọn.
Để đảm bảo mã này được tải dưới dạng mô-đun và không phải là tập lệnh thông thường, hãy thêm type="module"
vào các script
thẻ trong index.html
. Bất kỳ mã nào sử dụng import
hoặc export
phải sử dụng thuộc tính này:
...
<script type="module" src="functions.js"></script>
<script type="module" src="script.js"></script>
Tại thời điểm này, bạn sẽ có thể tải lại trang với các bản cập nhật và trang web bây giờ sẽ sử dụng các mô-đun. Hỗ trợ trình duyệt là rất cao, nhưng caniuse có sẵn để kiểm tra mà các trình duyệt hỗ trợ nó. Lưu ý rằng nếu bạn đang xem tệp dưới dạng liên kết trực tiếp đến tệp cục bộ, bạn sẽ gặp phải lỗi này:
OutputAccess to script at 'file:///Users/your_file_path/script.js' from origin 'null' has been blocked by CORS policy: Cross-origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.
Do chính sách CORS , Mô-đun phải được sử dụng trong môi trường máy chủ mà bạn có thể thiết lập cục bộ với máy chủ http hoặc trên internet với nhà cung cấp dịch vụ lưu trữ.
Mô-đun khác với các tập lệnh thông thường theo một số cách:
window
phạm vi global ( ).Các mô-đun vẫn thường được sử dụng cùng với các gói như Webpack để tăng cường hỗ trợ trình duyệt và các tính năng bổ sung, nhưng chúng cũng có sẵn để sử dụng trực tiếp trong các trình duyệt.
Tiếp theo, bạn sẽ khám phá thêm một số cách mà cú pháp import
và lệnh export
có thể được sử dụng.
Như đã trình bày trước đó, sử dụng export
cú pháp sẽ cho phép bạn nhập từng giá trị đã được xuất theo tên của chúng. Ví dụ: lấy phiên bản đơn giản này của functions.js
:
export function sum() {}
export function difference() {}
Điều này sẽ cho phép bạn nhập sum
và difference
theo tên bằng cách sử dụng dấu ngoặc nhọn:
import { sum, difference } from './functions.js'
Cũng có thể sử dụng bí danh để đổi tên hàm. Bạn có thể làm điều này để tránh xung đột đặt tên trong cùng một mô-đun. Trong ví dụ này, sum
sẽ được đổi tên thành add
và difference
sẽ được đổi tên thành subtract
.
import {
sum as add,
difference as subtract
} from './functions.js'
add(1, 2) // 3
Gọi add()
ở đây sẽ mang lại kết quả của sum()
hàm.
Sử dụng *
cú pháp, bạn có thể nhập nội dung của toàn bộ mô-đun vào một đối tượng. Trong trường hợp này, sum
và difference
sẽ trở thành các phương thức trên mathFunctions
đối tượng.
import * as mathFunctions from './functions.js'
mathFunctions.sum(1, 2) // 3
mathFunctions.difference(10, 3) // 7
Các giá trị nguyên thủy, biểu thức và định nghĩa hàm , hàm không đồng bộ , lớp và lớp khởi tạo đều có thể được xuất, miễn là chúng có mã định danh:
// Primitive values
export const number = 100
export const string = 'string'
export const undef = undefined
export const empty = null
export const obj = { name: 'Homer' }
export const array = ['Bart', 'Lisa', 'Maggie']
// Function expression
export const sum = (x, y) => x + y
// Function definition
export function difference(x, y) {
return x - y
}
// Asynchronous function
export async function getBooks() {}
// Class
export class Book {
constructor(name, author) {
this.name = name
this.author = author
}
}
// Instantiated class
export const book = new Book('Lord of the Rings', 'J. R. R. Tolkien')
Tất cả các xuất này có thể được nhập thành công. Loại xuất khác mà bạn sẽ khám phá trong phần tiếp theo được gọi là xuất mặc định.
Trong các ví dụ trước, bạn đã xuất nhiều bản xuất được đặt tên và nhập chúng riêng lẻ hoặc dưới dạng một đối tượng với mỗi lần xuất dưới dạng một phương thức trên đối tượng. Mô-đun cũng có thể chứa một kết xuất mặc định, sử dụng default
từ khóa. Một bản xuất mặc định sẽ không được nhập với dấu ngoặc nhọn, nhưng sẽ được nhập trực tiếp vào một mã định danh được đặt tên.
Ví dụ: lấy các nội dung sau cho functions.js
tệp:
export default function sum(x, y) {
return x + y
}
Trong script.js
tệp, bạn có thể nhập hàm mặc định như sum
sau:
import sum from './functions.js'
sum(1, 2) // 3
Điều này có thể nguy hiểm, vì không có hạn chế nào về những gì bạn có thể đặt tên cho bản xuất mặc định trong quá trình nhập. Trong ví dụ này, hàm mặc định được nhập như thể difference
nó thực sự là sum
hàm:
import difference from './functions.js'
difference(1, 2) // 3
Vì lý do này, nó thường được ưu tiên sử dụng hàng xuất khẩu có tên. Không giống như các bản xuất được đặt tên, các bản xuất mặc định không yêu cầu số nhận dạng — một giá trị nguyên thủy của chính nó hoặc hàm ẩn danh có thể được sử dụng làm bản xuất mặc định. Sau đây là một ví dụ về một đối tượng được sử dụng làm xuất mặc định:
export default {
name: 'Lord of the Rings',
author: 'J. R. R. Tolkien',
}
Bạn có thể nhập dữ liệu này như book
sau:
import book from './functions.js'
Tương tự, ví dụ sau minh họa xuất một hàm mũi tên ẩn danh làm xuất mặc định:
export default () => 'This function is anonymous'
Điều này có thể được nhập với những điều sau script.js
:
import anonymousFunction from './functions.js'
Xuất khẩu được đặt tên và xuất khẩu mặc định có thể được sử dụng song song với nhau, như trong mô-đun này xuất khẩu hai giá trị được đặt tên và một giá trị mặc định:
export const length = 10
export const width = 5
export default function perimeter(x, y) {
return 2 * (x + y)
}
Bạn có thể nhập các biến này và hàm mặc định như sau:
import calculatePerimeter, { length, width } from './functions.js'
calculatePerimeter(length, width) // 30
Bây giờ giá trị mặc định và giá trị được đặt tên đều có sẵn cho tập lệnh.
Thực tiễn thiết kế lập trình mô-đun cho phép bạn tách mã thành các thành phần riêng lẻ có thể giúp mã của bạn có thể tái sử dụng và nhất quán, đồng thời bảo vệ không gian tên chung. Một giao diện mô-đun có thể được triển khai bằng JavaScript gốc với từ khóa import
và export
.
Trong bài viết này, bạn đã tìm hiểu về lịch sử của các mô-đun trong JavaScript, cách tách các tệp JavaScript thành nhiều tập lệnh cấp cao nhất, cách cập nhật các tệp đó bằng cách sử dụng phương pháp mô-đun, import
và export
cú pháp cho các tệp xuất được đặt tên và mặc định.
Nguồn: https://www.digitalocean.com
#javascript
1622207074
Who invented JavaScript, how it works, as we have given information about Programming language in our previous article ( What is PHP ), but today we will talk about what is JavaScript, why JavaScript is used The Answers to all such questions and much other information about JavaScript, you are going to get here today. Hope this information will work for you.
JavaScript language was invented by Brendan Eich in 1995. JavaScript is inspired by Java Programming Language. The first name of JavaScript was Mocha which was named by Marc Andreessen, Marc Andreessen is the founder of Netscape and in the same year Mocha was renamed LiveScript, and later in December 1995, it was renamed JavaScript which is still in trend.
JavaScript is a client-side scripting language used with HTML (Hypertext Markup Language). JavaScript is an Interpreted / Oriented language called JS in programming language JavaScript code can be run on any normal web browser. To run the code of JavaScript, we have to enable JavaScript of Web Browser. But some web browsers already have JavaScript enabled.
Today almost all websites are using it as web technology, mind is that there is maximum scope in JavaScript in the coming time, so if you want to become a programmer, then you can be very beneficial to learn JavaScript.
In JavaScript, ‘document.write‘ is used to represent a string on a browser.
<script type="text/javascript">
document.write("Hello World!");
</script>
<script type="text/javascript">
//single line comment
/* document.write("Hello"); */
</script>
#javascript #javascript code #javascript hello world #what is javascript #who invented javascript
1616670795
It is said that a digital resource a business has must be interactive in nature, so the website or the business app should be interactive. How do you make the app interactive? With the use of JavaScript.
Does your business need an interactive website or app?
Hire Dedicated JavaScript Developer from WebClues Infotech as the developer we offer is highly skilled and expert in what they do. Our developers are collaborative in nature and work with complete transparency with the customers.
The technology used to develop the overall app by the developers from WebClues Infotech is at par with the latest available technology.
Get your business app with JavaScript
For more inquiry click here https://bit.ly/31eZyDZ
Book Free Interview: https://bit.ly/3dDShFg
#hire dedicated javascript developers #hire javascript developers #top javascript developers for hire #hire javascript developer #hire a freelancer for javascript developer #hire the best javascript developers
1589255577
As a JavaScript developer of any level, you need to understand its foundational concepts and some of the new ideas that help us developing code. In this article, we are going to review 16 basic concepts. So without further ado, let’s get to it.
#javascript-interview #javascript-development #javascript-fundamental #javascript #javascript-tips
1626321063
PixelCrayons: Our JavaScript web development service offers you a feature-packed & dynamic web application that effectively caters to your business challenges and provide you the best RoI. Our JavaScript web development company works on all major frameworks & libraries like Angular, React, Nodejs, Vue.js, to name a few.
With 15+ years of domain expertise, we have successfully delivered 13800+ projects and have successfully garnered 6800+ happy customers with 97%+ client retention rate.
Looking for professional JavaScript web app development services? We provide custom JavaScript development services applying latest version frameworks and libraries to propel businesses to the next level. Our well-defined and manageable JS development processes are balanced between cost, time and quality along with clear communication.
Our JavaScript development companies offers you strict NDA, 100% money back guarantee and agile/DevOps approach.
#javascript development company #javascript development services #javascript web development #javascript development #javascript web development services #javascript web development company
1670062320
I’m a huge fan of automation when the scenario allows for it. Maybe you need to keep track of guest information when they RSVP to your event, or maybe you need to monitor and react to feeds of data. These are two of many possible scenarios where you probably wouldn’t want to do things manually.
There are quite a few tools that are designed to automate your life. Some of the popular tools include IFTTT, Zapier, and Automate. The idea behind these services is that given a trigger, you can do a series of events.
In this tutorial, we’re going to see how to collect Twitter data with Zapier, store it in MongoDB using a Realm webhook function, and then run aggregations on it using the MongoDB query language (MQL).
There are a few requirements that must be met prior to starting this tutorial:
There is a Zapier free tier, but because we plan to use webhooks, which are premium in Zapier, a paid account is necessary. To consume data from Twitter in Zapier, a Twitter account is necessary, even if we plan to consume data that isn’t related to our account. This data will be stored in MongoDB, so a cluster with properly configured IP access and user permissions is required.
You can get started with MongoDB Atlas by launching a free M0 cluster, no credit card required.
While not necessary to create a database and collection prior to use, we’ll be using a zapier database and a tweets collection throughout the scope of this tutorial.
Since the plan is to store tweets from Twitter within MongoDB and then create queries to make sense of it, we should probably get an understanding of the data prior to trying to work with it.
We’ll be using the “Search Mention” functionality within Zapier for Twitter. Essentially, it allows us to provide a Twitter query and trigger an automation when the data is found. More on that soon.
As a result, we’ll end up with the following raw data:
{
"created_at": "Tue Feb 02 20:31:58 +0000 2021",
"id": "1356701917603238000",
"id_str": "1356701917603237888",
"full_text": "In case anyone is interested in learning about how to work with streaming data using Node.js, I wrote a tutorial about it on the @MongoDB Developer Hub. https://t.co/Dxt80lD8xj #javascript",
"truncated": false,
"display_text_range": [0, 188],
"metadata": {
"iso_language_code": "en",
"result_type": "recent"
},
"source": "<a href='https://about.twitter.com/products/tweetdeck' rel='nofollow'>TweetDeck</a>",
"in_reply_to_status_id": null,
"in_reply_to_status_id_str": null,
"in_reply_to_user_id": null,
"in_reply_to_user_id_str": null,
"in_reply_to_screen_name": null,
"user": {
"id": "227546834",
"id_str": "227546834",
"name": "Nic Raboy",
"screen_name": "nraboy",
"location": "Tracy, CA",
"description": "Advocate of modern web and mobile development technologies. I write tutorials and speak at events to make app development easier to understand. I work @MongoDB.",
"url": "https://t.co/mRqzaKrmvm",
"entities": {
"url": {
"urls": [
{
"url": "https://t.co/mRqzaKrmvm",
"expanded_url": "https://www.thepolyglotdeveloper.com",
"display_url": "thepolyglotdeveloper.com",
"indices": [0, 23]
}
]
},
"description": {
"urls": ""
}
},
"protected": false,
"followers_count": 4599,
"friends_count": 551,
"listed_count": 265,
"created_at": "Fri Dec 17 03:33:03 +0000 2010",
"favourites_count": 4550,
"verified": false
},
"lang": "en",
"url": "https://twitter.com/227546834/status/1356701917603237888",
"text": "In case anyone is interested in learning about how to work with streaming data using Node.js, I wrote a tutorial about it on the @MongoDB Developer Hub. https://t.co/Dxt80lD8xj #javascript"
}
The data we have access to is probably more than we need. However, it really depends on what you’re interested in. For this example, we’ll be storing the following within MongoDB:
{
"created_at": "Tue Feb 02 20:31:58 +0000 2021",
"user": {
"screen_name": "nraboy",
"location": "Tracy, CA",
"followers_count": 4599,
"friends_count": 551
},
"text": "In case anyone is interested in learning about how to work with streaming data using Node.js, I wrote a tutorial about it on the @MongoDB Developer Hub. https://t.co/Dxt80lD8xj #javascript"
}
Without getting too far ahead of ourselves, our analysis will be based off the followers_count
and the location
of the user. We want to be able to make sense of where our users are and give priority to users that meet a certain followers threshold.
Before we start connecting Zapier and MongoDB, we need to develop the middleware that will be responsible for receiving tweet data from Zapier.
Remember, you’ll need to have a properly configured MongoDB Atlas cluster.
We need to create a Realm application. Within the MongoDB Atlas dashboard, click the Realm tab.
For simplicity, we’re going to want to create a new application. Click the Create a New App button and proceed to fill in the information about your application.
From the Realm Dashboard, click the 3rd Party Services tab.
We’re going to want to create an HTTP service. The name doesn’t matter, but it might make sense to name it Twitter based on what we’re planning to do.
Because we plan to work with tweet data, it makes sense to call our webhook function tweet, but the name doesn’t truly matter.
With the exception of the HTTP Method, the defaults are fine for this webhook. We want the method to be POST because we plan to create data with this particular webhook function. Make note of the Webhook URL because it will be used when we connect Zapier.
The next step is to open the Function Editor so we can add some logic behind this function. Add the following JavaScript code:
exports = function (payload, response) {
const tweet = EJSON.parse(payload.body.text());
const collection = context.services.get("mongodb-atlas").db("zapier").collection("tweets");
return collection.insertOne(tweet);
};
In the above code, we are taking the request payload, getting a handle to the tweets collection within the zapier database, and then doing an insert operation to store the data in the payload.
There are a few things to note in the above code:
When we call our function, a new document should be created within MongoDB.
By default, the function will not deploy when saving. After saving, make sure to review and deploy the changes through the notification at the top of the browser window.
So, we know the data we’ll be working with and we have a MongoDB Realm webhook function that is ready for receiving data. Now, we need to bring everything together with Zapier.
For clarity, new Twitter matches will be our trigger in Zapier, and the webhook function will be our event.
Within Zapier, choose to create a new “Zap,” which is an automation. The trigger needs to be a Search Mention in Twitter, which means that when a new Tweet is detected using a search query, our events happen.
For this example, we’re going to use the following Twitter search query:
url:developer.mongodb.com -filter:retweets filter:safe lang:en -from:mongodb -from:realm
The above query says that we are looking for tweets that include a URL to developer.mongodb.com. The URL doesn’t need to match exactly as long as the domain matches. The query also says that we aren’t interested in retweets. We only want original tweets, they have to be in English, and they have to be detected as safe for work.
In addition to the mentioned search criteria, we are also excluding tweets that originate from one of the MongoDB accounts.
In theory, the above search query could be used to see what people are saying about the MongoDB Developer Hub.
With the trigger in place, we need to identify the next stage of the automation pipeline. The next stage is taking the data from the trigger and sending it to our Realm webhook function.
As the event, make sure to choose Webhooks by Zapier and specify a POST request. From here, you’ll be prompted to enter your Realm webhook URL and the method, which should be POST. Realm is expecting the payload to be JSON, so it is important to select JSON within Zapier.
We have the option to choose which data from the previous automation stage to pass to our webhook. Select the fields you’re interested in and save your automation.
The data I chose to send looks like this:
{
"created_at": "Tue Feb 02 20:31:58 +0000 2021",
"username": "nraboy",
"location": "Tracy, CA",
"follower_count": "4599",
"following_count": "551",
"message": "In case anyone is interested in learning about how to work with streaming data using Node.js, I wrote a tutorial about it on the @MongoDB Developer Hub. https://t.co/Dxt80lD8xj #javascript"
}
The fields do not match the original fields brought in by Twitter. It is because I chose to map them to what made sense for me.
When deploying the Zap, anytime a tweet is found that matches our query, it will be saved into our MongoDB cluster.
With tweet data populating in MongoDB, it’s time to start querying it to make sense of it. In this fictional example, we want to know what people are saying about our Developer Hub and how popular these individuals are.
To do this, we’re going to want to make use of an aggregation pipeline within MongoDB.
Take the following, for example:
[
{
"$addFields": {
"follower_count": {
"$toInt": "$follower_count"
},
"following_count": {
"$toInt": "$following_count"
}
}
}, {
"$match": {
"follower_count": {
"$gt": 1000
}
}
}, {
"$group": {
"_id": {
"location": "$location"
},
"location": {
"$sum": 1
}
}
}
]
There are three stages in the above aggregation pipeline.
We want to understand the follower data for the individual who made the tweet, but that data comes into MongoDB as a string rather than an integer. The first stage of the pipeline takes the follower_count
and following_count
fields and converts them from string to integer. In reality, we are using $addFields
to create new fields, but because they have the same name as existing fields, the existing fields are replaced.
The next stage is where we want to identify people with more than 1,000 followers as a person of interest. While people with fewer followers might be saying great things, in this example, we don’t care.
After we’ve filtered out people by their follower count, we do a group based on their location. It might be valuable for us to know where in the world people are talking about MongoDB. We might want to know where our target audience exists.
The aggregation pipeline we chose to use can be executed with any of the MongoDB drivers, through the MongoDB Atlas dashboard, or through the CLI.
You just saw how to use Zapier with MongoDB to automate certain tasks and store the results as documents within the NoSQL database. In this example, we chose to store Twitter data that matched certain criteria, later to be analyzed with an aggregation pipeline. The automations and analysis options that you can do are quite limitless.
If you enjoyed this tutorial and want to get engaged with more content and like-minded developers, check out the MongoDB Community.
This content first appeared on MongoDB.
Original article source at: https://www.thepolyglotdeveloper.com/