Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the Modeling of Feed Collection

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly explains "how to realize the modeling of Feed Collection". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to realize the modeling of Feed Collection.

MEAN stack can be summarized as follows:

M = MongoDB/Mongoose.js. Popular database, for node. For js, it is an elegant ODM.

E = Express.js: a lightweight Web application framework.

A = Angular.js: a robust framework for creating HTML5 and JavaScript-rich Web applications.

N = Node.js server-side JavaScript interpreter.

MEAN stack is a modern replacement for LAMP (Linux, Apache, MySQL,PHP / Python) stack, and LAMP was the mainstream way to build Web applications in the late 1990s.

Angular.js will not be used in this application because it is not intended to build a HTML user interface. Instead, you create a REST API without a user interface, but it can be used as the basis for any interface, such as a Web site, an Android application, or an iOS application. It can also be said that we are building REST API on ME (a) N stack, but that's not the point! # # what is REST API?

REST stands for Representational State Transfer and is a lighter alternative to the SOAP and WSDL XML-based API protocols.

REST uses the client-server model, where the server is a HTTP server, and the client sends HTTP behaviors (GET, POST, PUT, DELETE), as well as URL-encoded variable parameters and a URL. The URL specifies the scope of the object, and the server responds with the result code and a valid JavaScript Object Notation (JSON).

Because the server replies with JSON, MongoDB and JSON interact well, and all components use JavaScript, MEAN stack is a good fit for the application in this use case. After you start defining the data model, you will see some examples of JSON.

CRUD acronyms are often used to describe database operations. CRUD stands for create, read, update, and delete. These database operations map well to HTTP actions:

POST: the customer wants to insert or create an object.

GET: the client wants to read an object.

PUT: the customer wants to update an object.

DELETE: the customer wants to delete an object.

After defining the API, these operations will become more intuitive. Some common HTTP result codes commonly used in REST APIs are as follows:

200-"OK"

"Created" (used with POST).

400-"Bad Request" (required parameters may be lost).

401-"Unauthorized" (authentication parameter missing).

403-"Forbidden" (verified, but insufficient permissions).

404-"Not Found"

A complete description can be found in the RFC documentation, which is listed in Resources at the end of this blog. All of the above result code will be used in this application, and some examples will be shown later. Why start with REST API?

Deploying a REST API can lay the foundation for building any type of application. As mentioned earlier, these applications may be web-based or specifically designed for certain platforms, such as Android or iOS.

Nowadays, there are many companies that no longer use HTTP or Web interfaces when building applications, such as Uber, WhatsApp, Postmates and Wash.io. From a simple application to a powerful platform, REST API can greatly simplify the implementation of other interfaces and applications in the process. # # establishing REST API

Here you will create a RSS Aggregator, similar to Google Reader, and the application will consist of two main components:

REST API

Feed Grabber (similar to Google Reader)

This series of blog posts will focus on the creation of this REST API, without paying attention to the complexity of RSS feeds. Now, the code for Feed Grabber can be found in github repository, and details can be found in the resources listed in the blog post. The steps required to build this API are described below. First, the data model is defined according to the specific requirements:

Store user information in a user account

Track the RSS feeds that needs to be monitored

Pull the feed record to the database

Track user feed subscriptions

Track which subscription feed the user will read

Users need to be able to do the following:

Set up an account

Subscribe or unsubscribe to feed

Read the feed record

Mark the reading status of the feed/ record (read / unread)

# # data Modeling

Data modeling in MongoDB is not discussed in depth here, and the details can be found in the materials listed at the end of the blog post. This use case requires four collections to manage this information:

Feed collection

Feed entry collection

User collection

User-feed-entry mapping collection

# # Feed Collection

Let's go to a piece of code, and the modeling of Feed Collection can be done through the following JSON documents:

{"_ id": ObjectId ("523b1153a2aa6a3233a913f8"), "requiresAuthentication": false, "modifiedDate": ISODate ("2014-08-29T17:40:22Z"), "permanentlyRemoved": false, "feedURL": "http://feeds.feedburner.com/eater/nyc","title":" Eater NY "," bozoBitSet ": false," enabled ": true," etag ":" 4bL78iLSZud2iXd/vd10mYC32BE "," link ":" http://ny.eater.com/","permanentRedirectURL": null " "description": "The New York City Restaurant, Bar, and Nightlife Blog"}

If you are proficient in relational database technology, you will understand databases, tables, columns, and rows. In MongoDB, most relational concepts can be mapped. At a higher level, MongoDB deployments support one or more databases. A database may contain multiple collection, which is similar to tables in traditional relational databases. There will be multiple document in Collection, and at a high level, document is equivalent to a row in a relational database. It should be noted here that document in MongoDB does not have a preset format. Instead, each document can have one or more key-value pairs, where the values can be simple, such as dates, or complex, such as an array of address objects.

The JSON document above is an example of Eater Blog's RSS feed, which tracks all restaurant information in New York. Therefore, there may be many fields here, and the main focus in the use case is URL and description in feed. Description is very important, so when building a mobile application, it can be a good summary for feed.

The other fields in JSON are for internal use, and the very important field is _ id. In MongoDB, each document needs to have a _ id field. If you create a document,MongoDB without-- id, it will be automatically added for you. In MongoDB, this field is the existence of the primary key, so MongoDB ensures that the field value is unique within the collection range. # # Feed Entry Collection

After feed, the use case also expects to trace the feed record. Here is an example of an Feed Entry Collection document:

{"_ id": ObjectId ("523b1153a2aa6a3233a91412"), "description": "Buzzfeed asked a bunch of people...", "title": "Cronut Mania: Buzzfeed asked a bunch of people...", "summary": "Buzzfeed asked a bunch of people that were...", "content": [{"base": "http://ny.eater.com/"," type ":" text/html " "value": "LOTS OF HTML HERE", "language": "en"}], "entryID": "tag:ny.eater.com,2013://4.560508", "publishedDate": ISODate ("2013-09-17T20:45:20Z"), "link": "http://ny.eater.com/archives/2013/09/cronut_mania_41 .php", "feedID": ObjectId ("523b1153a2aa6a3233a913f8")}

Again, you must also have a _ id field here, and you can also see the description, title, and summary fields. For the content field, an array is used here, and a document is also stored in the data. MongoDB allows the nesting of document in this way, and this usage is also necessary in many scenarios, because use cases often require centralized storage of information.

The entryID field uses the tag format to avoid copying feed records. One thing to note here is the use of feedID and ObjectId-- the value is _ id of Eater Blog document. This provides a reference model similar to foreign keys in relational databases. Therefore, if you expect to see the feed document associated with this ObjectId, you can take the value 523b1153a2aa6a3233a913f8 and query feed collection on _ id, which returns Eater Blog document. # # User Collection

Here is a document that the user needs to use:

{"id": ObjectId ("54ad6c3ae764de42070b27b1"), "active": true, "email": "testuser1@example.com", "firstName": "Test", "lastName": "User1", "sp_api_key_id": "6YQB0A8VXM0X8RVDPPLRHBI7J", "sp_api_key_secret": "veBw/YFx56Dl0bbiVEpvbjF", "lastLogin": ISODate ("2015-01-07T17:26:18.996Z") "created": ISODate ("2015-01-07T17:26:18.995Z"), "subs": [ObjectId ("523b1153a2aa6a3233a913f8"), ObjectId ("54b563c3a50a190b50f4d63b"),}

The user should have an email address, first name and last name. Again, there are sp_api_key_id and sp_api_key_secret-- these two fields will be used in conjunction with Stormpath, a user-managed API, in subsequent sections. The last field, subs, is a subscription array. The subs field indicates which feeds the user subscribes to. # # User-Feed-Entry Mapping Collection

{"_ id": ObjectId ("523b2fcc054b1b8c579bdb82"), "read": true, "user_id": ObjectId ("54ad6c3ae764de42070b27b1"), "feed_entry_id": ObjectId ("523b1153a2aa6a3233a91412"), "feed_id": ObjectId ("523b1153a2aa6a3233a913f8")}

The last collection allows you to map users to feeds and track which feeds has been read. Here, a Boolean type (true/false) is used to mark the read and the unread. # # some functional requirements of REST API

As mentioned above, users need to be able to do the following:

Set up an account

Subscribe or unsubscribe to feed

Read the feed record

Mark feed / record's reading status (read / unread)

In addition, the user needs to be able to reset the password. The following table shows how these operations map to HTTP routes and actions.

In a production environment, HTTP (HTTPS) security requires a standard way to send sensitive information, such as passwords. # # implementing authentication in the real world through Stormpath

In a robust real-world application, it is inevitable to provide user authentication. Therefore, a secure way to manage users, passwords, and password resets is needed.

In this use case, authentication can be done in several ways. One of these is to use Node.js with Passport Plugin, which is often used in social media account authentication, such as Facebook or Twitter. However, Stormpath is also a very good approach. Stormpath is a user management-as-a-service that supports authentication and authorization through API keys. Basically, Stormpath maintains a database of user details and passwords so that the client application API can call Stormpath REST API to authenticate the user.

The following figure shows the request and response flow after using Stormpath.

In detail, Stormpath provides a security key for each application, which is defined by their services. For example, you can define an application as "Reader Production" or "Reader Test". Defining these two applications is useful if you are developing and testing applications all the time, because adding and deleting test users can be very frequent. Here, Stormpath also provides an API Key Properties file. Stormpath also allows password attributes to be defined based on the requirements of the application, such as:

No less than 8 characters

Must contain case

Must contain a number

Must contain 1 non-alphabetic character

Stormpath tracks all users and assigns their API keys (for REST API authentication), which greatly simplifies the application establishment process because you no longer need to write code for authenticating users. # # Node.js

Node.js is the runtime environment for server-side and network applications. Node.js uses JavaScript and is suitable for many different platforms, such as Linux, Microsoft Windows, and Apple OS X.

Node.js applications need to be built through multiple library modules, and there are already a lot of resources in the community, which will be used in subsequent application building.

In order to use Node.js, developers need to define package.json files to describe the dependencies of the application and all libraries.

Node.js Package Manager installs copies of all libraries to a subdirectory of the application directory, node_modules/. This has some benefits because it isolates library versions of different applications and avoids the code complexity caused by the uniform installation of all libraries into a standard directory, such as / usr/lib.

The command npm establishes the node_modules/ directory, as well as all required libraries.

The following is the JavaScript under the package.json file:

{"name": "reader-api", "main": "server.js", "dependencies": {"express": "~ 4.10.0", "stormpath": "~ 0.7.5", "express-stormpath": "~ 0.5.9", "mongodb": "~ 1.4.26", "mongoose": "~ 3.8.0" "body-parser": "~ 1.10.0", "method-override": "~ 2.3.0", "morgan": "~ 1.5.0", "winston": "~ 0.8.3", "express-winston": "~ 0.2.9", "validator": "~ 3.27.0", "path": "~ 0.4.9" "errorhandler": "~ 1.3.0", "frisby": "~ 0.8.3", "jasmine-node": "~ 1.14.5", "async": "~ 0.9.0"}}

The application is named reader-api, and the master file is named server.js, followed by a series of dependent libraries and their versions. Some of these libraries are designed to parse HTTP queries. Here, we will use frisby as the test tool, and jasmine-node will be used to run frisby scripts.

Among these libraries, async is particularly important. If you have never used node.js, note that node.js uses an asynchronous mechanism. Therefore, any blocking input/output (Istroke O) operation (such as a read from socket or a database query) takes a callback function as the last parameter, and then continues to control the flow, only after the blocking operation ends. Let's look at a simple example to understand this.

Function foo () {someAsyncFunction (params, function (err, results) {console.log ("one");}); console.log ("two");}

In the above example, your imaginary output might be:

Onetwo

But the actual output is:

Twoone

The reason for this result is the asynchronous mechanism used by Node.js, and the code for printing "one" may be executed in subsequent callback functions. The reason why it is possible is that it only happens under certain circumstances. This uncertainty caused by asynchronous programming is called non-deterministic execution. For many programming tasks, doing so can achieve high performance, but it is very troublesome in scenarios where sequencing is required. An ideal order can be obtained by using the following rules:

ActionArray = [function one (cb) {someAsyncFunction (params, function (err, results) {if (err) {cb (new Error ("There was an error"));} console.log ("one"); cb (null);}), function two (cb) {console.log ("two"); cb (null);}] async.series (actionArray) At this point, I believe you have a deeper understanding of "how to realize the modeling of Feed Collection". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report