In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly shows you "how to build a lightweight location analysis report service API in Node", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "how to build a lightweight location analysis report service API in Node".
The location defined by latitude and longitude can be used in conjunction with other data to generate insight for the enterprise, which is called location analysis.
Companies operating globally use location analysis throughout the value chain, for example, to locate users, provide services, and run targeted advertisements. With the rise of social media and mobile devices, the use of location analysis has increased worldwide.
In this tutorial, we will learn how to build a lightweight location analysis reporting service, API, in Node.js. At the end of this tutorial, you will be able to build this type of API for your own project. You will also have a better understanding of error handling and good file structure in Node.js
Let's get started!
prerequisite
To continue this tutorial, you need to have the following conditions.
Familiar with Node.js, Express and Git
Visual Studio Code Editor
Heroku account
Postman account
Set the file structure
First, we need to set up our file structure. Open your terminal and create a new directory where you will store all the files of the project. On your terminal, type the following command, followed by the name of the folder, lars.
Mkdir lars
Open the lars working directory in the VS code editor.
Code.
You will see your VS Code window open.
Visual Studio Code window
Initialize the working directory by opening your terminal in Visual Studio and running npm init-y.
If you want to run this command from a terminal on an operating system other than VS Code, navigate to the lars directory and run the following command.
Npm init-y
The above code automatically generates the package.json file.
VS Code displays the created package.json file
In this tutorial, we will use Express as a dependency. Install Express by running the following command.
Npm install express-save
Command to install Express as a dependency
After installing Express, you will notice that a node_modules folder has been created. To confirm that you have installed Express, please check your package.json file and you will see that Express is installed as a dependency.
The node_modules folder is created and the Express is added to the package.json.
We need to import Express into our application because it is a npm module. Create a new file called app.js in the same directory as your package.json file.
A screenshot of the VS code window shows that the app.js has been created.
In your app.js file, run the following code requireExpress.
Const express = require ('express')
Import Express
Now, call Express to create your application, routing, and the port on which your application will run.
Const app = express ()
Node.js is modular, which means it divides your application into modules, or various files, and exports each file. We will export app using the export keyword.
Module.exports = app
App.js file
Next, create another file named server.js in the same directory as the app.js file. Require imports the app.js file into the server.js file.
Const app = require ('. / app')
Create a file called config.env in the same directory as server.js. The config.env file will contain all the [process.env] (https://nodejs.org/dist/latest-v8.x/docs/api/process.html) all keys that our application needs) that our application needs. In the config.env file, create a PORT variable and set PORT to listen on port 8000.
PORT=8000
After importing the application, create a constant named port in the server.js file. Set it to the PORT variable you just created and a default port of 3000.
Const port = process.env.PORT | | 3000
Finally, we will use the .listen () method to set up the application to listen on that port.
App.listen (port, () = > {console.log (`App listening on ${port} `)}); build a route
Every time you visit a web page or an application running on the web, you are sending out a HTTP request. The server responds with data from the background or database, which is called HTTP response.
When you create a resource on a web application, you are calling a POST request. Similarly, if you try to delete or update a resource on a Web application, you are calling a DELETE, PATCH, or UPDATE request. Let's set up a route to process these requests.
Create a folder called routes in your working directory and create a file called analyticsRoute.js in it. Require is expressed in the analyticsRoute.js file to set the routing of the API.
Const express = require ('express')
We also need to require our application module from the app.js file.
Const app = require ('.. / app')
Then we create our route.
Const router = express.Router ()
Finally, we want to export the router.
Module.exports = router; establish controller
We need to create a file for the controller and import it into our analyticsRoutes file. First, create a folder called controllers in your working directory.
Our API will use the IP address and coordinates provided by the user to calculate the distance and location. Our request needs to accept this information and requests from users.
We will use a POST request because the user is in req.body. To save this information, we need to require a fs module (file system) in the controller.
Processing the request for POST
Create a file called storeController.js in the controllers folder. In the storeController.js file, we need to import the fs module and the fsPromises.readFile () method to process the returned promise, that is, the user's IP address and coordinates.
To install the fs module, open your terminal in your working directory and run the following command.
Npm i fs-save
Enter the following code at the top of your file.
Const fsp = require ('fs'). Promises;const fs = require (' fs')
Next, we will create a controller that handles the routing of our POST requests. We will use the exports keyword and create an asynchronous middleware function that takes three parameters.
Req: represents the request object
Res: represents the response object
Next: the function is called immediately after the middleware output.
PostAnalytics = async (req, res, next) = > {}
Now we will save the properties of the data object in req.body to the reportAnalytics array. We will set up a Date () object to save the creation date of any data in a createdAt key.
ReportAnalytics.push ({... req.body, createdAt: new Date ()})
We will create a file called storeAnalytics.json and use JSON.stringify () to save the contents of our reportAnalytics array as a string.
Await fsp.writeFile (`${_ dirname} / storeAnalytics.json`, JSON.stringify (reportAnalytics))
When the user makes a POST request, we need to check whether the storeAnalytics.json file exists. If the file exists, we need to read the file and save the output.
The output contains a constant called reportFile, which stores the contents of the file being read. In reportFile, use JSON.parse to convert the contents of the file into a JavaScript object.
/ / checks if file existsif (fs.existsSync (`${_ dirname} / storeAnalytics.json`) {/ / If the file exists, reads the file const reportFile = await fsp.readFile (` ${_ dirname} / storeAnalytics.json`, 'utf-8') / / converts the file to JavaScript ObjectreportAnalytics = JSON.parse (reportFile)} else {/ / if file does not exist return (' File does not exist');}
The [fs.existsSync ()] (https://www.geeksforgeeks.org/node-js-fs-existssync-method/) method checks synchronously to see if the file exists. It takes the ${_ dirname} / storeAnalytics.json path as its single parameter and points to the location of the file we want to check.
We combine the await keyword with reportFile to wait for the result of reading the file with the fsp.readFile () method. Next, we use (${_ dirname} / storeAnalytics.json) to specify the path to the file we want to read. We set the encoding format to utf-8, which converts what is read from the file into a string.
JSON.parse () converts reportFile to a JavaScript object and stores it in the reportAnalytics array. The code in the else statement block runs only if the file does not exist. Finally, we use the return statement because we want to stop the execution of the function after the code runs.
If the file is successfully read, created, and saved in storeAnalytics.json, we need to send a response. We will use the response object (res), which is the second argument to our asynchronous postAnalytics function.
Res.status. Json ({status: 'success', data: {message:' IP and Coordinates successfully taken'}})
We will respond with a status success and data information IP and Coordinates successfully taken.
Your storeController.js file should look like the screenshot below.
Processing the request for GET
We need to create another controller file to process our GET request. When a user sends a GET request to API, we will calculate their location based on their IP address and coordinates.
Create a file called fetchController.js in the controllers folder. Fs in the storeController.js file, we need the require module and the fsPromises.readFile () method to process the returned promise.
Const fsp = require ('fs'). Promises;const fs = require (' fs')
Let's create a controller to handle our routing of GET requests. We will use similar middleware functions and parameters to process the above POST request.
Exports.getAnalytics = async (req, res, next) = > {}
In the getAnalytics middleware, enter the following code to obtain the IP address from the requested query.
Const {ip} = req.query
Now, create an empty array to store the contents of the req.body.
Let reportAnalytics = []
As we did before, we need to check whether the storeAnalytics.json file exists. If the file exists, we will use JSON.parse on reportFile to convert the contents of the file into a JavaScript object.
If (fs.existsSync (`${_ dirname} / storeAnalytics.json`) {const reportFile = await fsp.readFile (` ${_ dirname} / storeAnalytics.json`, 'utf-8') reportAnalytics = JSON.parse (reportFile)} else {return (' File does not exist');}
Now we can save the user's IP address and coordinates in the storeAnalytics.json file. Whenever the user requests that the geographic location be calculated according to the coordinates provided, the IP address will be included in the request in the form of a query.
Now that we have the IP address from the req.query object, we can write code to check that the IP address provided in the req.query object is the same as the IP address stored in the storeAnalytics.json file.
For (let iTuno; I el.ip = = ip & & new Date (el.createdAt) > hourAgo)
In the code block above, we created a constant named hourAgo and set it to a Date object. We use the setHours () method to set hourAgo to getHours ()-1 for the last hour.
When the current IP address in the reportAnalytics file is equal to or equal to the IP address passed in req.query, it means that the data was created in the last hour, and getReport creates a constant that is set to a new array.
Create a constant called coordinatesArray, which will store only the coordinates that have been saved in the getReport array.
Const coordinatesArray = getReport.map (element = > element.coordinates)
Next, we need to calculate the location with coordinates. We need to iterate through the coordinatesArray and calculate the location by passing in two values saved as coordinates.
Let totalLength = 0; for (let iTuno; I {res.status (err.statusCode). Json ({status: err.status, error: err, message: err.message, stack: err.stack,});}
We will create a function called sendErrorDev, which takes two parameters, err for error and res for response. Response.status receives the wrong statusCode and responds with JSON data.
In addition, we will create a function called sendErrorProd, which will handle errors encountered by API in a production environment.
Const sendErrorProd = (err, res) = > {if (err.isOperational) {res.status (err.statusCode) .json ({status: err.status, message: err.message});} else {console.error ('Error', err) Res.status. Json ({status: 'error', message:' Something went wrong'})}}
In your utilities folder, create a file called appError.js and enter the following code.
Class AppError extends Error {constructor (message, statusCode) {super (message); this.statusCode = statusCode; this.status = `${statusCode}` .startswith ('4')? 'fail':' error'; this.isOperational = true; Error.captureStackTrace (this, this.constructor);}} module.exports = AppError
We will create a class called AppError, which extends the Error object.
Then we will create a constructor that will initialize the object of this class. It takes two parameters, called message and statusCode. The super method calls the constructor with one parameter, passes it into message, and gets access to the properties and methods of the constructor.
Next, we set the statusCode property of the constructor to statusCode. We set the status property of the constructor to any statusCode that starts with 4, for example, set 404 statusCode to fail or error.
Create another file called catchAsync.js and add the following code to it.
Module.exports = fn = > {return (req, res, next) = > {fn (req, res, next) .catch (next);} add error handling to the controller file
The Require appError.js file and catchAsync.js file are in your storeController.js and fetchController.js files. Place these two import statements at the top of the code in the two files.
Const catchAsync = require ('.. / utilities/catchAsync'); const AppError = require ('.. / utilities/appError')
In the storeController.js and fetchController.js files, wrap your function with the catchAsync () method, as shown below.
/ / For storeController.js fileexports.postAnalytics = catchAsync (async (req, res, next) = > {.} / / For fetchController.js fileexports.getAnalytics = catchAsync (async (req, res, next) = > {...}
Next, in your fetchController.js file, run the AppError class.
For (let iTuno; I {if (isIp (req.query.ip)! = true) {return res.status (404). Json ({status: 'fail', data: {message:' Invalid IP, not found.'}})} next ();}
Run the following command to install the necessary dependencies for our API.
Npm install body-parser cors dotenv express fs is-ip joi morgan ndb nodemon
Your app.js file should look like the screenshot below.
App.js file
Under the scripts section of your package.json file, add the following code snippet.
"start:dev": "node server.js", "debug": "ndb server.js"
Your package.json file should look like the screenshot below.
Package.json file
Update your analyticsRoute.js file with the following code.
Const express = require ('express'); const app = require ('.. / app'); const router = express.Router (); const validateIP = require ('.. / utilities/Validation/validateIP'); const storeController = require ('.. / controllers/storeController'); const fetchController = require ('.. / controllers/fetchController'); router.route ('/ analytics') .post (storeController.postAnalytics) .get (validateIP.validateIP, fetchController.getAnalytics); module.exports = router
Now we have completed the construction of our location analysis API! Now, let's test our code to make sure it works.
Test API
We will use Postman to test our API. Let's start our API to make sure it is running on our terminal.
Node server.js
You will see the following output on your terminal.
Terminal
Our API is hosted on Heroku, and its final output should look like the following.
You can test the API yourself in the hosted documentation.
Https://documenter.getpostman.com/view/13856921/TzXumeXS
The above is all the contents of the article "how to build a lightweight location Analysis report Service API in Node". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.