投稿時間:2022-05-26 22:25:04 RSSフィード2022-05-26 22:00 分まとめ(31件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
IT 情報システムリーダーのためのIT情報専門サイト IT Leaders ローコード開発ツール「SPIRAL」新版、画像やCSSなどを管理画面からアップロードしてサイトを制作可能に | IT Leaders https://it.impress.co.jp/articles/-/23230 ローコード開発ツール「SPIRAL」新版、画像やCSSなどを管理画面からアップロードしてサイトを制作可能にITLeadersパイプドビッツは年月日、ローコード開発ツール「SPIRALver」の新バージョンについてβ版をリリースした。 2022-05-26 21:30:00
python Pythonタグが付けられた新着投稿 - Qiita VSCodeのターミナルで「pyenv global」で「pyenv version」が書き換わらない https://qiita.com/sentencebird/items/7b573c158ddb9401bf00 pyenvg 2022-05-26 21:59:11
python Pythonタグが付けられた新着投稿 - Qiita Dogelog Player is now Self Hosting https://qiita.com/j4n_bur53/items/c9bb7661e84766e8f870 prolog 2022-05-26 21:57:40
js JavaScriptタグが付けられた新着投稿 - Qiita Dogelog Player is now Self Hosting https://qiita.com/j4n_bur53/items/c9bb7661e84766e8f870 prolog 2022-05-26 21:57:40
Ruby Rubyタグが付けられた新着投稿 - Qiita Ruby初心者が「TryRuby」で引っかかったところ https://qiita.com/onumakunz/items/149af0b6d609ceea200d tryruby 2022-05-26 21:45:50
Ruby Rubyタグが付けられた新着投稿 - Qiita 【Rails】(解決)空のデータベースに対してnil?などのメソッドで条件分岐してもエラーがでる(undefined method `〇〇◯' for nil:NilClass (NoMethodError)) https://qiita.com/syoichi0425/items/927c9d7dea81734a3070 intelcoreigbmhzlpddrxruby 2022-05-26 21:00:51
Ruby Rubyタグが付けられた新着投稿 - Qiita 【Rails】created_atを2ステップで日本語に設定し、ビューに表示させる方法 https://qiita.com/study_matome/items/a5903654c0f8270a1eef createdat 2022-05-26 21:00:39
AWS AWSタグが付けられた新着投稿 - Qiita Exam Readiness DOP : 分野 4:ポリシーと標準の自動化 https://qiita.com/tetsuya_tech/items/baa999857d805fae3842 awsdop 2022-05-26 21:35:30
AWS AWSタグが付けられた新着投稿 - Qiita 【CLF-C01対策】AWS Well-Architected フレームワーク https://qiita.com/moritalous/items/c5e1b1bd6cb505f4b97c awswellarchitected 2022-05-26 21:14:20
Ruby Railsタグが付けられた新着投稿 - Qiita 【Rails】(解決)空のデータベースに対してnil?などのメソッドで条件分岐してもエラーがでる(undefined method `〇〇◯' for nil:NilClass (NoMethodError)) https://qiita.com/syoichi0425/items/927c9d7dea81734a3070 intelcoreigbmhzlpddrxruby 2022-05-26 21:00:51
Ruby Railsタグが付けられた新着投稿 - Qiita 【Rails】created_atを2ステップで日本語に設定し、ビューに表示させる方法 https://qiita.com/study_matome/items/a5903654c0f8270a1eef createdat 2022-05-26 21:00:39
技術ブログ Developers.IO 【レポート】サーバーレスを活用したイベント駆動アーキテクチャ(AWS-45) #AWSSummit https://dev.classmethod.jp/articles/aws-summit-japan-online-2022-aws-45/ awsawssummit 2022-05-26 12:33:12
海外TECH MakeUseOf How to Stop Forgetting Things at Work https://www.makeuseof.com/stop-forgetting-things-at-work/ workif 2022-05-26 12:45:13
海外TECH MakeUseOf How to Enable Automatic Image Labels in Microsoft Edge https://www.makeuseof.com/enable-microsoft-edge-automatic-image-labels/ description 2022-05-26 12:30:14
海外TECH MakeUseOf You Can Now Customize Your Pronouns in The Sims 4: Here's How https://www.makeuseof.com/the-sims-4-how-to-customize-pronouns/ You Can Now Customize Your Pronouns in The Sims Here x s HowThe Sims has added another layer of inclusivity in a May update Let s explore how you can use it to customize each of your Sim s pronouns 2022-05-26 12:10:34
海外TECH DEV Community How to Remove all Routes from the Navigation Tree in Flutter? https://dev.to/kuldeeptarapara/how-to-remove-all-routes-from-the-navigation-tree-in-flutter-fe2 How to Remove all Routes from the Navigation Tree in Flutter What are routes In Flutter Route is a widget used to navigate to a different screen The navigation system is one of the most important processes in any mobile app development journey Also its a trusted choice to hire Flutter developer to make your mobile app development journey successful The Route is used to navigate from one screen to another in Flutter For Example There is a screen that contains the image and once the user taps on that image the new screen will display details about that image Basically there are two types of methods in routes Navigator push MethodThis method is used to Navigate to the second route You can check here how to navigate the new screen in flutter Navigator pop MethodThe navigator pop method is used to return to the first route Below we have mentioned the methods that remove all routes Method pushNamedAndRemoveUntilThe first method is used when a developer builds an auth like sign in or sign out application For example When a user logs out from an application and afterward if the user re entered that application they must have moved to the sign in screen So in this scenario this method will help remove all routes in the stack so that the user cannot go back to the previous routes after they successfully log out We need to forcefully move the user to the login routes to the stack before showing any screen Navigator of context pushNamedAndRemoveUntil login Route route gt false The above code indicates that routes always return false this condition is used to remove all routes from the stack Route route gt false Following these conditions will remove all the routes from the stack except the login route we pushed Method pushAndRemoveUntilThe second method is used when the user wants to remove all routes from the stack and add the new screen usingMaterialPageRoute Builder context gt LoginScreen Here developers can put any screen instead of Login Screen LoginScreen Navigator of context pushAndRemoveUntil MaterialPageRoute builder context gt LoginScreen Route route gt false Method popUntilAnother alternative is popUntil If you do not use named routes and we want the navigator to the first screen or First active you can use the popUntil method Navigator of context popUntil route gt route isFirst Below I mentioned the Example with full source code import package flutter material dart void main runApp const NavApp class NavApp extends StatelessWidget const NavApp Key key super key key override Widget build BuildContext context return MaterialApp debugShowCheckedModeBanner false onGenerateRoute settings Handle if settings name return MaterialPageRoute builder context gt const HomeScreen Handle details id var uri Uri parse settings name if uri pathSegments length amp amp uri pathSegments first details var id uri pathSegments return MaterialPageRoute builder context gt DetailScreen id id return MaterialPageRoute builder context gt const UnknownScreen class HomeScreen extends StatelessWidget const HomeScreen Key key super key key override Widget build BuildContext context return Scaffold appBar AppBar body Center child TextButton child const Text View Details onPressed Navigator pushNamed context details class DetailScreen extends StatelessWidget final String id const DetailScreen Key key required this id super key key override Widget build BuildContext context return Scaffold appBar AppBar body Center child Column mainAxisAlignment MainAxisAlignment center children Text Viewing details for item id TextButton child const Text Pop onPressed Navigator of context pushAndRemoveUntil MaterialPageRoute builder context gt const HomeScreen Route route gt false class UnknownScreen extends StatelessWidget const UnknownScreen Key key super key key override Widget build BuildContext context return Scaffold appBar AppBar body const Center child Text Page not found Output Conclusion So In this article we learned about How to remove all routes from the stack and also learned about how to navigate to a new screen and remove all screens Thank you for reading our article Hope you enjoyed our article Keep visiting Bosc Tech for more upcoming content 2022-05-26 12:47:37
海外TECH DEV Community How to choose a website feedback tool? https://dev.to/oktuned/how-to-choose-a-website-feedback-tool-2kpi How to choose a website feedback tool A website feedback tool is essential for any business today that wants to optimize its customer experience and improve conversion rates However not all feedback tools are created equal so it s important to know what you re looking for before selecting Choosing the right website feedback tool can be a daunting task There are many options to choose from and there is no one size fits all solution In this article we will explore some of the most popular feedback tools available on the market today and highlight their strengths and weaknesses What is a website feedback tool Website feedback is a way to collect valuable insights and feedback from customers and website visitors about your website It helps you understand how people interact with your site what they like and what they don t like They can be used to improve user experience on the website track customer opinions and provide insights into how people use the site A website feedback tool is a great way to track and manage critical feedback from your website visitors These tools help collect analyze and help understand the visitor s behavior and preferences What are the types of website feedback Voice of the Customer Surveys The Voice of the Customer Surveys help companies understand what their customers want and how they feel about a specific product or service They help them get feedback on what they need to change to improve their customer experience The goals of the voice of customer survey tools like Hubspot Feedbackify Survicate etc are to collect insights to improve products and services as well as to provide overall customer satisfaction and excellent customer support Voc surveys come in many forms from open ended questions to multiple choice and yes no questionnaires It supports regular NPS CSAT and CES surveys as well Voice of the customer surveys helps collect feedback from customers and potential customers on how they view a product or service that can be used to assess customer satisfaction and measure their willingness to buy it again in the future With that said Voc surveys come in various forms like Pop up surveys immediately appear on a specific trigger Exit surveys when you attempt to leave the website Feedback Widgets A feedback widget is a way for a company to get feedback from its customers and visitors They are typically embedded buttons on the company s website which offer customers an opportunity to provide feedback on the website products or services they were provided with Feedback widgets provided by customer feedback tools like Rapidr Hotjar etc support interactive forms to get feedback from its customers about their experience with the product or services Feedback widgets also help developers get instant feedback about how users find their product fix bugs improve design and develop new features Feedback widgets are much more than just a way to collect feedback they re also an opportunity to learn about your users and improve your site based on their needs and wants and provide excellent customer support Feedback widgets can take many forms Some may be simple questionnaires while others may be more complex with multiple questions and answers Feedback Forms Feedback forms are an easy way to get information about your site and what people think about it Feedback forms allow you to collect data on specific topics or aspects of your site that you want more insight into For example if you want to know what people think about the design of your site you can ask for their opinion through a specific question or set of questions on the form Tools such as Typeform Google Forms etc are used as feedback forms on various websites Feedback Pages Companies use the community feedback tools such as Rapidr Uservoice and UserEcho to get feedback from their customers They are usually in the form of feedback forums and feedback pages Feedback pages are a great way to collect feedback from your customers and make adjustments accordingly Companies create dedicated feedback pages to provide an open forum to their customers to suggest new ideas report bugs and understand their views on the features they are developing When feedback pages are combined with public roadmaps and product changelog they create an end to end solution to close the user feedback loop With tools like Rapidr companies start a complete product development cycle by listening to customers ideas asking for their opinions prioritizing features and feedback based on business objectives and showcasing progress with public roadmaps and changelogs Visual feedback Visual feedback also called usability feedback directly captures feedback from users Visual feedback tools provide a more visual way of giving feedback by pointing out specific page elements including buttons text images or elements and giving feedback on those Visual feedback tools help designers and developers understand how users interact with their products such as BugHerd Usersnap Marker etc Traditional Surveys Traditional surveys allow you to ask questions and get answers in a quantitative manner They also help you understand your audience s demographics better and find out what their preferences are when it comes to content design etc Online survey tools such as SurveyMonkey Qualtrics and Mopinion are used for marketing research customer satisfaction employee engagement and internal processes They can help companies make decisions on how to improve their products and services by gathering feedback from their customers or employees Reviews and Ratings The customer is king and customer reviews and ratings are the new forms of royalty According to a research more than of customers read online reviews before buying Reviews and ratings are a great way to get an idea of the quality of a product or service They help people make informed decisions before buying something or using some product A review evaluates something such as a product service or performance Reviews are written by customers and maybe about a product or an experience A rating is an assessment of one item s relative quality compared to another item Ratings can be good poor excellent etc but are usually on some kind of scale like or stars Online Review and Rating tools such as TrustPilot Bazaarvoice Podium etc allow users to share their thoughts on products and services online in reviews and collect user ratings on their products or services What are the benefits of using a website feedback tool Website feedback tools will not only help you collect feedback from website visitors but push your company in the right direction for growth They allow you to understand better what your customers think about your product or service Benefits of using website feedback tools Website feedback tools help assess the performance of a website and its design It also provides insight into what visitors think about the website and its experience Website feedback tools help identify potential problems with a website and product before they become too severe or provide essential insights into how visitors are interacting with your site They help you improve your conversion rates by providing access to valuable data that will help you create a better user experience for your visitors Website feedback tools can help you understand what your visitors want and need and understand what they like or dislike about your site Creates a one on one connection with the customers It helps you improve customer satisfaction by collecting their feedback and giving them a voice on how they feel about your product or service It gives you insights into the user experience which is vital for developing new features or changing existing features How to choose a website feedback tool Many website feedback tools are available in the market but there is no one size fits all Choosing a tool that best suits your needs and budget is essential Many factors can help you choose the best website feedback tool for your needs like its features price and compatibility with other software To select a website feedback tool you need to consider the following factors Which features do you need in a website feedback tool What type of feedback are you trying to collect What are your preferences in terms of design and usability Why are you collecting feedback What is your goal Is it mainly for customer feedback or employee feedback A good website feedback tool should have all these features Simple intuitive interfaceEasy installationCustomizable questionnaires that suit your needsResponsive customer supportTrack Feature requests Capture feature requests from customers and manage and prioritize features all in one place with feature tracking feature voting tools like Rapidr Uservoice etc Usability Testing Understand how customers use your product to fix UI and user experience issues with usability testing tools like UserTesting Usersnap etc Bug Reporting Track bugs from your customers and team members either with a form or visual feedback and update your stakeholders whenever those bugs are resolved with bug tracking tools like Rapidr BugHerd etc Collect NPS amp CSAT Scores Traditional survey tools are used to collect Net Promoters Score NPS and Customer Satisfaction Score CSAT from customers to gauge customer loyalty and satisfaction try SurveyMonkey Survicate etc Collect Feedback Create and share a dedicated feedback page for collecting all types of customer feedback prioritize ideas also with showing progress with a public roadmap and close the feedback loop with feature release notifications with customer feedback tools like Rapidr etc Online Reviews Collect online reviews and ratings from your customers which would act as social proof and help build trust between the company and customers with review platforms like TrustPilot Bazaarvoice etc Improve Conversions Improve conversions and understand when do users signup what happens after a visitor lands on the page and what features and content drive them to pay with website analytics tools like Hotjar Pendo etc can help In app Feedback Collect feedback from users in the app and track user behavior without sending them elsewhere with in app feedback tools like Rapidr Pendo etc to improve the overall user experience How to get started with website Feedback While there are many tools to help you capture organize and prioritize feedback you should consider the one that enables you to uncover the insights from the feedback without jumping through hoops The ideal software should not only do all the basics but take all the other housekeeping off your plate It should notify customers about new releases thus completing the feedback loop providing actionable insights and rallying everyone around the roadmap Rapidr does all that and even more Rapidr helps SaaS companies be more customer centric by consolidating feedback scattered across different apps prioritizing requests communicating with customers and closing the feedback loop Sign up for a free now or check out our affordable pricing plans to learn whether Rapidr is right for you 2022-05-26 12:35:34
海外TECH DEV Community Build a REST API with Rust and MongoDB - Actix web Version https://dev.to/hackmamba/build-a-rest-api-with-rust-and-mongodb-actix-web-version-ei1 Build a REST API with Rust and MongoDB Actix web VersionREST API has become the De Facto for connecting and transferring data from one source to another It offers a set of guidelines and architectural patterns for designing and developing web services This post will discuss building a user management application with Rust using the Actix web framework and MongoDB At the end of this tutorial we will learn how to structure a Rust application build a REST API and persist our data using MongoDB Actix web is an HTTP web framework written in Rust with performance and productivity support Actix web ships with features like type safety reusability logging static file serving and much more that developers can leverage to build scalable applications MongoDB is a document based database management program used as an alternative to relational databases MongoDB supports working with large sets of distributed data with options to store or retrieve information seamlessly The complete source code is available in this repository PrerequisitesTo fully grasp the concepts presented in this tutorial experience with Rust is required Experience with MongoDB isn t a requirement but it s nice to have We will also be needing the following A MongoDB account to host database Signup is completely free Postman or any API testing application Let s code Getting StartedTo get started we need to navigate to the desired directory and run the command below in our terminal cargo new actix mongo api amp amp cd actix mongo apiThis command creates a Rust project called actix mongo api and navigates into the project directory Next we proceed to install the required dependencies by modifying the dependencies section of the Cargo toml file as shown below other code section goes here dependencies actix web serde dotenv dependencies mongodb version default features false features sync actix web is a Rust based framework for building web applications serde is a framework for serializing and deserializing Rust data structures E g convert Rust structs to JSON dotenv is a library for managing environment variables dependencies mongodb is a driver for connecting to MongoDB It also specifies the required version and the feature type Sync API We need to run the command below to install the dependencies cargo build Application Entry PointWith the project dependencies installed modify the main rs file in the src folder to the following use actix web get App HttpResponse HttpServer Responder get async fn hello gt impl Responder HttpResponse Ok json Hello from rust and mongoDB actix web main async fn main gt std io Result lt gt HttpServer new App new service hello bind localhost run await The snippet above does the following Imports the required dependenciesCreates a hello handler that uses the Rust macro to specify the HTTP method the route path and returns a JSON of Hello from rust and mongoDB Uses the actix web main macro to run the main function asynchronously within the actix runtime The main function does the following Creates a new server using HttpServer struct that uses a closure to serve incoming requests using the App instance The App also registers the hello handler HttpServer is the backbone of our application it takes care of request handling the maximum number of connections allowed layered security e t c while App handles application logic like request handlers middlewares routing e t c Configures the server to run asynchronously and process HTTP requests on localhost Next we can test our application by running the command below in our terminal cargo run Module system in RustA module in Rust is a mechanism for splitting code into reusable components and managing visibility between them Modules help us maintain a good project structure for our project To do this we need to navigate to the src folder and create api models and repository folder with the corresponding mod rs file to manage visibility api is for modularizing API handlers models is for modularizing data logics repository is for modularizing database logics Adding reference to the ModulesTo use the code in the modules we need to declare them as a module and import them into the main rs file add the modules mod api mod models mod repository use actix web get App HttpResponse HttpServer Responder the remaining part of our code goes here Setting up MongoDBWith that done we need to log in or sign up into our MongoDB account Click the project dropdown menu and click on the New Project button Enter the rust api as the project name click Next and click Create Project Click on Build a DatabaseSelect Shared as the type of database Click on Create to setup a cluster This might take sometime to setup Next we need to create a user to access the database externally by inputting the Username Password and then clicking on Create User We also need to add our IP address to safely connect to the database by clicking on the Add My Current IP Address button Then click on Finish and Close to save changes On saving the changes we should see a Database Deployments screen as shown below Connecting our application to MongoDBWith the configuration done we need to connect our application with the database created To do this click on the Connect buttonClick on Connect your application change the Driver to Rust and the Version as shown below Then click on the copy icon to copy the connection string Setup Environment VariableNext we must modify the copied connection string with the user s password we created earlier and change the database name To do this first we need to create a env file in the root directory and in this file add the snippet copied MONGOURI mongodb srv lt YOUR USERNAME HERE gt lt YOUR PASSWORD HERE gt cluster eakf mongodb net myFirstDatabese retryWrites true amp w majoritySample of a properly filled connection string below MONGOURI mongodb srv malomz malomzPassword cluster eakf mongodb net golangDB retryWrites true amp w majority Creating REST APIsWith the setup done we need to create a model to represent our application data To do this we need to navigate to the models folder and in this folder create a user model rs file and add the snippet below use mongodb bson oid ObjectId use serde Serialize Deserialize derive Debug Serialize Deserialize pub struct User serde rename id skip serializing if Option is none pub id Option lt ObjectId gt pub name String pub location String pub title String The snippet above does the following Imports the required dependenciesUses the derive macro to generate implementation support for formatting the output serializing and deserializing the data structure Creates a User struct with required properties We also added field attributes to the id property to rename and ignore the field if it is empty PS The pub modifier makes the struct and its property public and can be accessed from other files modules Next we must register the user model rs file as part of the models module To do this open the mod rs in the models folder and add the snippet below pub mod user model Create a User EndpointWith the model fully set up and made available to be consumed we can now create our database logic to create a user To do this First we need to navigate to the repository folder and in this folder create a mongodb repo rs file and add the snippet below use std env extern crate dotenv use dotenv dotenv use mongodb bson extjson de Error results InsertOneResult sync Client Collection use crate models user model User pub struct MongoRepo col Collection lt User gt impl MongoRepo pub fn init gt Self dotenv ok let uri match env var MONGOURI Ok v gt v to string Err gt format Error loading env variable let client Client with uri str uri unwrap let db client database rustDB let col Collection lt User gt db collection User MongoRepo col pub fn create user amp self new user User gt Result lt InsertOneResult Error gt let new doc User id None name new user name location new user location title new user title let user self col insert one new doc None ok expect Error creating user Ok user The snippet above does the following Imports the required dependenciesCreates a MongoRepo struct with a col field to access MongoDB collectionCreates an implementation block that adds methods to the MongoRepo structAdds an init method to the implementation block to load the environment variable creates a connection to the database and returns an instance of the MongoRepo structAdds a create user method that takes in a self and new user as parameters and returns the created user or an error Inside the method we created a new document using the User struct Then we use the self referencing the MongoRepo struct to access the insert one function from the collection to create a new user and handle errors Finally we returned the created user information PS The None specified when creating a new document tells MongoDB to automatically generate the user s id Next we must register the mongodb repo rs file as part of the repository module To do this open the mod rs in the repository folder and add the snippet below pub mod mongodb repos Secondly we need to create a handler that uses the create user method from the repository to create a user To do this we need to navigate to the api folder and in this folder create a user api rs file and add the snippet below use crate models user model User repository mongodb repo MongoRepo use actix web post web Data Json HttpResponse post user pub async fn create user db Data lt MongoRepo gt new user Json lt User gt gt HttpResponse let data User id None name new user name to owned location new user location to owned title new user title to owned let user detail db create user data match user detail Ok user gt HttpResponse Ok json user Err err gt HttpResponse InternalServerError body err to string The snippet above does the following Imports the required dependenciesUses the routing macro to specify HTTP method and corresponding routeCreates a create user handler that takes in the db a type to the MongoRepo and a new user as parameters Inside the handler we created a data variable for creating a user inserted it into the database using the db create user method and returned the correct response if the insert was successful or error if any PS The Data and Json struct used in defining the parameter is for managing application state shared across routes and extracting JSON data from request payloads respectively Finally we need to modify our application entry point to include the create user handler To do this we need to navigate to the main rs file and modify it as shown below mod api mod models mod repository modify imports below use actix web web Data App HttpServer use api user api create user use repository mongodb repo MongoRepo actix web main async fn main gt std io Result lt gt let db MongoRepo init let db data Data new db HttpServer new move App new app data db data clone service create user bind run await The snippet above does the following Imports the required dependenciesCreates a db variable to establish a connection to MongoDB by calling the init method and adds it to a new instance of the Data struct so that the database state can be available across the application scope Uses the app data and service function to add the application data and the handler to the App instance PS The move keyword attached to the closure gives it ownership of the MongoDB configuration Get a User EndpointTo get the details of a user we must first modify the mongodb repo rs file by adding a get user method to the implementation block use std env extern crate dotenv use dotenv dotenv use mongodb bson extjson de Error oid ObjectId doc modify here results InsertOneResult sync Client Collection use crate models user model User pub struct MongoRepo col Collection lt User gt impl MongoRepo pub fn init gt Self init code goes here pub fn create user amp self new user User gt Result lt InsertOneResult Error gt create user code goes here pub fn get user amp self id amp String gt Result lt User Error gt let obj id ObjectId parse str id unwrap let filter doc id obj id let user detail self col find one filter None ok expect Error getting user s detail Ok user detail unwrap The snippet above does the following Modifies the dependencies to include oid ObjectId and docAdds a get user method that takes in a self and id as parameters and returns the user detail or an error Inside the method we converted the id to an ObjectId and used it as a filter to get matching document Then we use the self referencing the MongoRepo struct to access the find one function from the collection to get the details of the user and handle errors Finally we returned the created user information Secondly we need to modify user api rs by creating a handler that uses the get user method from the repository to get a user use crate models user model User repository mongodb repo MongoRepo use actix web post get modify here web Data Json Path modify here HttpResponse post user pub async fn create user db Data lt MongoRepo gt new user Json lt User gt gt HttpResponse create user code goes here get user id pub async fn get user db Data lt MongoRepo gt path Path lt String gt gt HttpResponse let id path into inner if id is empty return HttpResponse BadRequest body invalid ID let user detail db get user amp id match user detail Ok user gt HttpResponse Ok json user Err err gt HttpResponse InternalServerError body err to string The snippet above does the following Modifies the dependencies to include get and PathUses the routing macro to specify HTTP method corresponding route and route parameterCreates a get user handler that takes in the db a type to the MongoRepo and a path for accessing route path as parameters Inside the handler we created an id variable to get the user s id get the user s details from the database using the db get user method We returned the correct response if the request was successful or error if any Finally we need to modify our application entry point main rs to include the get user handler by importing the handler and adding a new service for it mod api mod models mod repository modify imports below use actix web web Data App HttpServer use api user api create user get user import the handler here use repository mongodb repo MongoRepo actix web main async fn main gt std io Result lt gt let db MongoRepo init let db data Data new db HttpServer new move App new app data db data clone service create user service get user add this bind run await Edit a User EndpointTo edit a user we must first modify the mongodb repo rs file by adding an edit user method to the implementation block use std env extern crate dotenv use dotenv dotenv use mongodb bson extjson de Error oid ObjectId doc results InsertOneResult UpdateResult modify here sync Client Collection use crate models user model User pub struct MongoRepo col Collection lt User gt impl MongoRepo pub fn init gt Self init code goes here pub fn create user amp self new user User gt Result lt InsertOneResult Error gt create user code goes here pub fn get user amp self id amp String gt Result lt User Error gt get user code goes here pub fn update user amp self id amp String new user User gt Result lt UpdateResult Error gt let obj id ObjectId parse str id unwrap let filter doc id obj id let new doc doc set id new user id name new user name location new user location title new user title let updated doc self col update one filter new doc None ok expect Error updating user Ok updated doc The snippet above does the following Modifies the dependencies to include UpdateResultAdds an update user method that takes in a self id and new user parameters and returns the updated user detail or an error Inside the method we converted the id to an ObjectId created a filter variable to get the matching document we wanted to update and used the doc macro to update the document fields Then we use the self referencing the MongoRepo struct to access the update one function from the collection to update the user matching the filter specified and handle errors Finally we returned the updated user information Secondly we need to modify user api rs by creating a handler that uses the update user method from the repository to update a user use crate models user model User repository mongodb repo MongoRepo use actix web post get put modify here web Data Json Path HttpResponse use mongodb bson oid ObjectId add this post user pub async fn create user db Data lt MongoRepo gt new user Json lt User gt gt HttpResponse create user code goes here get user id pub async fn get user db Data lt MongoRepo gt path Path lt String gt gt HttpResponse get user code goes here put user id pub async fn update user db Data lt MongoRepo gt path Path lt String gt new user Json lt User gt gt HttpResponse let id path into inner if id is empty return HttpResponse BadRequest body invalid ID let data User id Some ObjectId parse str amp id unwrap name new user name to owned location new user location to owned title new user title to owned let update result db update user amp id data match update result Ok update gt if update matched count let updated user info db get user amp id return match updated user info Ok user gt HttpResponse Ok json user Err err gt HttpResponse InternalServerError body err to string else return HttpResponse NotFound body No user found with specified ID Err err gt HttpResponse InternalServerError body err to string The snippet above does the following Modifies the dependencies to include put and ObjectIdUses the routing macro to specify HTTP method corresponding route and route parameterCreates an update user handler that takes in the db a type to the MongoRepo path and new user as parameters Inside the handler we created an id variable to get the user s id update the user s details from the database using the db update user method by passing in the updated user s information Finally we checked if the update was successful and returned the updated user or error if any Finally we need to modify our application entry point main rs to include the update user handler by importing the handler and adding a new service for it mod api mod models mod repository modify imports below use actix web web Data App HttpServer use api user api create user get user update user import the handler here use repository mongodb repo MongoRepo actix web main async fn main gt std io Result lt gt let db MongoRepo init let db data Data new db HttpServer new move App new app data db data clone service create user service get user service update user add this bind run await Delete a User EndpointTo delete a user we must first modify the mongodb repo rs file by adding an delete user method to the implementation block use std env extern crate dotenv use dotenv dotenv use mongodb bson extjson de Error oid ObjectId doc results InsertOneResult UpdateResult DeleteResult modify here sync Client Collection use crate models user model User pub struct MongoRepo col Collection lt User gt impl MongoRepo pub fn init gt Self init code goes here pub fn create user amp self new user User gt Result lt InsertOneResult Error gt create user code goes here pub fn get user amp self id amp String gt Result lt User Error gt get user code goes here pub fn update user amp self id amp String new user User gt Result lt UpdateResult Error gt update user code goes here pub fn delete user amp self id amp String gt Result lt DeleteResult Error gt let obj id ObjectId parse str id unwrap let filter doc id obj id let user detail self col delete one filter None ok expect Error deleting user Ok user detail The snippet above does the following Modifies the dependencies to include DeleteResultAdds a delete user method that takes in a self and id as parameters and returns the deleted user detail or an error Inside the method we converted the id to an ObjectId and created a filter variable to get the matching document we wanted to delete Then we use the self referencing the MongoRepo struct to access the delete one function from the collection to delete the user matching the filter specified and handle errors Finally we returned the deleted user information Secondly we need to modify user api rs by creating a handler that uses the delete user method from the repository to delete a user use crate models user model User repository mongodb repo MongoRepo use actix web post get put delete modify here web Data Json Path HttpResponse use mongodb bson oid ObjectId add this post user pub async fn create user db Data lt MongoRepo gt new user Json lt User gt gt HttpResponse create user code goes here get user id pub async fn get user db Data lt MongoRepo gt path Path lt String gt gt HttpResponse get user code goes here put user id pub async fn update user db Data lt MongoRepo gt path Path lt String gt new user Json lt User gt gt HttpResponse update user code goes here delete user id pub async fn delete user db Data lt MongoRepo gt path Path lt String gt gt HttpResponse let id path into inner if id is empty return HttpResponse BadRequest body invalid ID let result db delete user amp id match result Ok res gt if res deleted count return HttpResponse Ok json User successfully deleted else return HttpResponse NotFound json User with specified ID not found Err err gt HttpResponse InternalServerError body err to string The snippet above does the following Modifies the dependencies to include deleteUses the routing macro to specify HTTP method corresponding route and route parameterCreates a delete user handler that takes in the db a type to the MongoRepo and path as parameters Inside the handler we created an id variable to get the user s id and delete the user from the database using the db delete user method by passing in the id Finally we returned the appropriate response or error if any Finally we need to modify our application entry point main rs to include the delete user handler by importing the handler and adding a new service for it mod api mod models mod repository modify imports below use actix web web Data App HttpServer use api user api create user get user update user delete user import the handler here use repository mongodb repo MongoRepo actix web main async fn main gt std io Result lt gt let db MongoRepo init let db data Data new db HttpServer new move App new app data db data clone service create user service get user service update user service delete user add this bind run await Get all Users EndpointTo get the list of users we must first modify the mongodb repo rs file by adding a get all users method to the implementation block use std env extern crate dotenv use dotenv dotenv use mongodb bson extjson de Error oid ObjectId doc results InsertOneResult UpdateResult DeleteResult sync Client Collection use crate models user model User pub struct MongoRepo col Collection lt User gt impl MongoRepo pub fn init gt Self init code goes here pub fn create user amp self new user User gt Result lt InsertOneResult Error gt create user code goes here pub fn get user amp self id amp String gt Result lt User Error gt get user code goes here pub fn update user amp self id amp String new user User gt Result lt UpdateResult Error gt update user code goes here pub fn delete user amp self id amp String gt Result lt DeleteResult Error gt delete user code goes here pub fn get all users amp self gt Result lt Vec lt User gt Error gt let cursors self col find None None ok expect Error getting list of users let users cursors map doc doc unwrap collect Ok users The snippet above adds a get all users method that takes in a self as a parameter and returns the list of users or an error Inside the method we use the self referencing the MongoRepo struct to access the find function from the collection without any filter so that it can match all the documents inside the database and handle errors Finally we returned the list of users Secondly we need to modify user api rs by creating a handler that uses the get all users method from the repository to get list of users use crate models user model User repository mongodb repo MongoRepo use actix web post get put delete web Data Json Path HttpResponse use mongodb bson oid ObjectId post user pub async fn create user db Data lt MongoRepo gt new user Json lt User gt gt HttpResponse create user code goes here get user id pub async fn get user db Data lt MongoRepo gt path Path lt String gt gt HttpResponse get user code goes here put user id pub async fn update user db Data lt MongoRepo gt path Path lt String gt new user Json lt User gt gt HttpResponse update user code goes here delete user id pub async fn delete user db Data lt MongoRepo gt path Path lt String gt gt HttpResponse delet user code goes here get users pub async fn get all users db Data lt MongoRepo gt gt HttpResponse let users db get all users match users Ok users gt HttpResponse Ok json users Err err gt HttpResponse InternalServerError body err to string The snippet above does the following Uses the routing macro to specify HTTP method and corresponding routeCreates a get all users handler that uses the db delete user method to get the list of users Then we returned the list of users or error if any Finally we need to modify our application entry point main rs to include the get all users handler by importing the handler and adding a new service for it mod api mod models mod repository modify imports below use actix web web Data App HttpServer use api user api create user get user update user delete user get all users import the handler here use repository mongodb repo MongoRepo actix web main async fn main gt std io Result lt gt let db MongoRepo init let db data Data new db HttpServer new move App new app data db data clone service create user service get user service update user service delete user service get all users add this bind run await With that done we can test our application by running the command below in our terminal cargo run ConclusionThis post discussed how to modularize a Rust application build a REST API and persist our data using MongoDB You may find these resources helpful Actix webMongoDB Rust DriverSerde Serializing and Deserializing library Rust Environment Loader 2022-05-26 12:32:38
海外TECH DEV Community Build a REST API with Rust and MongoDB - Rocket Version https://dev.to/hackmamba/build-a-rest-api-with-rust-and-mongodb-rocket-version-ah5 Build a REST API with Rust and MongoDB Rocket VersionREST API has become the De Facto for connecting and transferring data from one source to another It offers a set of guidelines and architectural patterns for designing and developing web services This post will discuss building a user management application with Rust using the Rocket framework and MongoDB At the end of this tutorial we will learn how to structure a Rust application build a REST API and persist our data using MongoDB Rocket is an HTTP web framework written in Rust with priorities on security flexibility and speed Rocket ships with features like type safety reusability logging static file serving and much more that developers can leverage to build scalable applications with less code MongoDB is a document based database management program used as an alternative to relational databases MongoDB supports working with large sets of distributed data with options to store or retrieve information seamlessly The complete source code is available in this repository PrerequisitesTo fully grasp the concepts presented in this tutorial experience with Rust is required Experience with MongoDB isn t a requirement but it s nice to have We will also be needing the following A MongoDB account to host database Signup is completely free Postman or any API testing application Let s code Getting StartedTo get started we need to navigate to the desired directory and run the command below in our terminal cargo new rocket mongo api amp amp cd rocket mongo apiThis command creates a Rust project called rocket mongo api and navigates into the project directory Next we proceed to install the required dependencies by modifying the dependencies section of the Cargo toml file as shown below other code section goes here dependencies rocket version rc features json serde dotenv dependencies mongodb version default features false features sync rocket version rc features json is a Rust based framework for building web applications It also specifies the required version and the feature type json serde is a framework for serializing and deserializing Rust data structures E g convert Rust structs to JSON dotenv is a library for managing environment variables dependencies mongodb is a driver for connecting to MongoDB It also specifies the required version and the feature type Sync API We need to run the command below to install the dependencies cargo build Application Entry PointWith the project dependencies installed modify the main rs file in the src folder to the following macro use extern crate rocket use rocket get http Status serde json Json get fn hello gt Result lt Json lt String gt Status gt Ok Json String from Hello from rust and mongoDB launch fn rocket gt rocket build mount routes hello The snippet above does the following Imports the required dependenciesCreates a hello handler that uses the Rust macro to specify the HTTP method the route path and returns a JSON of Hello from rust and mongoDB Uses the launch macro to run the main function asynchronously and starts the server The main function creates a new server using the build function and mounts the hello handler to a route Next we can test our application by running the command below in our terminal cargo runRocket runs the development server on or localhost Module system in RustA module in Rust is a mechanism for splitting code into reusable components and managing visibility between them Modules help us maintain a good project structure for our project To do this we need to navigate to the src folder and create api models and repository folder with the corresponding mod rs file to manage visibility api is for modularizing API handlers models is for modularizing data logics repository is for modularizing database logics Adding reference to the ModulesTo use the code in the modules we need to declare them as a module and import them into the main rs file add the modules mod api mod models mod repository macro use extern crate rocket use rocket get http Status serde json Json the remaining part of our code goes here Setting up MongoDBWith that done we need to log in or sign up into our MongoDB account Click the project dropdown menu and click on the New Project button Enter the rust api as the project name click Next and click Create Project Click on Build a DatabaseSelect Shared as the type of database Click on Create to setup a cluster This might take sometime to setup Next we need to create a user to access the database externally by inputting the Username Password and then clicking on Create User We also need to add our IP address to safely connect to the database by clicking on the Add My Current IP Address button Then click on Finish and Close to save changes On saving the changes we should see a Database Deployments screen as shown below Connecting our application to MongoDBWith the configuration done we need to connect our application with the database created To do this click on the Connect buttonClick on Connect your application change the Driver to Rust and the Version as shown below Then click on the copy icon to copy the connection string Setup Environment VariableNext we must modify the copied connection string with the user s password we created earlier and change the database name To do this first we need to create a env file in the root directory and in this file add the snippet copied MONGOURI mongodb srv lt YOUR USERNAME HERE gt lt YOUR PASSWORD HERE gt cluster eakf mongodb net myFirstDatabese retryWrites true amp w majoritySample of a properly filled connection string below MONGOURI mongodb srv malomz malomzPassword cluster eakf mongodb net golangDB retryWrites true amp w majority Creating REST APIsWith the setup done we need to create a model to represent our application data To do this we need to navigate to the models folder and in this folder create a user model rs file and add the snippet below use mongodb bson oid ObjectId use serde Serialize Deserialize derive Debug Serialize Deserialize pub struct User serde rename id skip serializing if Option is none pub id Option lt ObjectId gt pub name String pub location String pub title String The snippet above does the following Imports the required dependenciesUses the derive macro to generate implementation support for formatting the output serializing and deserializing the data structure Creates a User struct with required properties We also added field attributes to the id property to rename and ignore the field if it is empty PS The pub modifier makes the struct and its property public and can be accessed from other files modules Next we must register the user model rs file as part of the models module To do this open the mod rs in the models folder and add the snippet below pub mod user model Create a User EndpointWith the model fully set up and made available to be consumed we can now create our database logic to create a user To do this First we need to navigate to the repository folder and in this folder create a mongodb repo rs file and add the snippet below use std env extern crate dotenv use dotenv dotenv use mongodb bson extjson de Error results InsertOneResult sync Client Collection use crate models user model User pub struct MongoRepo col Collection lt User gt impl MongoRepo pub fn init gt Self dotenv ok let uri match env var MONGOURI Ok v gt v to string Err gt format Error loading env variable let client Client with uri str uri unwrap let db client database rustDB let col Collection lt User gt db collection User MongoRepo col pub fn create user amp self new user User gt Result lt InsertOneResult Error gt let new doc User id None name new user name location new user location title new user title let user self col insert one new doc None ok expect Error creating user Ok user The snippet above does the following Imports the required dependenciesCreates a MongoRepo struct with a col field to access MongoDB collectionCreates an implementation block that adds methods to the MongoRepo structAdds an init method to the implementation block to load the environment variable creates a connection to the database and returns an instance of the MongoRepo structAdds a create user method that takes in a self and new user as parameters and returns the created user or an error Inside the method we created a new document using the User struct Then we use the self referencing the MongoRepo struct to access the insert one function from the collection to create a new user and handle errors Finally we returned the created user information PS The None specified when creating a new document tells MongoDB to automatically generate the user s id Next we must register the mongodb repo rs file as part of the repository module To do this open the mod rs in the repository folder and add the snippet below pub mod mongodb repos Secondly we need to create a handler that uses the create user method from the repository to create a user To do this we need to navigate to the api folder and in this folder create a user api rs file and add the snippet below use crate models user model User repository mongodb repo MongoRepo use mongodb results InsertOneResult use rocket http Status serde json Json State post user data lt new user gt pub fn create user db amp State lt MongoRepo gt new user Json lt User gt gt Result lt Json lt InsertOneResult gt Status gt let data User id None name new user name to owned location new user location to owned title new user title to owned let user detail db create user data match user detail Ok user gt Ok Json user Err gt Err Status InternalServerError The snippet above does the following Imports the required dependenciesUses the routing macro to specify HTTP method route and indicates that the handler expects body data Creates a create user handler that takes in the db a type to the MongoRepo and a new user as parameters Inside the handler we created a data variable for creating a user inserted it into the database using the db create user method and returned the correct response if the insert was successful or error if any PS The amp State and Json struct used in defining the parameter is for managing application state shared across routes and extracting JSON data from request payloads respectively Finally we need to modify our application entry point to include the create user handler To do this we need to navigate to the main rs file and modify it as shown below mod api mod models mod repository macro use extern crate rocket add imports below use api user api create user use repository mongodb repo MongoRepo launch fn rocket gt let db MongoRepo init rocket build manage db mount routes create user The snippet above does the following Imports the required dependenciesCreates a db variable to establish a connection to MongoDB by calling the init method and adds it to the manage function to make the database state available across the application scopeUses the app data and service function to add the application data and the handler to the App instanceGet a User EndpointTo get the details of a user we must first modify the mongodb repo rs file by adding a get user method to the implementation block use std env extern crate dotenv use dotenv dotenv use mongodb bson extjson de Error oid ObjectId doc modify here results InsertOneResult sync Client Collection use crate models user model User pub struct MongoRepo col Collection lt User gt impl MongoRepo pub fn init gt Self init code goes here pub fn create user amp self new user User gt Result lt InsertOneResult Error gt create user code goes here pub fn get user amp self id amp String gt Result lt User Error gt let obj id ObjectId parse str id unwrap let filter doc id obj id let user detail self col find one filter None ok expect Error getting user s detail Ok user detail unwrap The snippet above does the following Modifies the dependencies to include oid ObjectId and docAdds a get user method that takes in a self and id as parameters and returns the user detail or an error Inside the method we converted the id to an ObjectId and used it as a filter to get matching document Then we use the self referencing the MongoRepo struct to access the find one function from the collection to get the details of the user and handle errors Finally we returned the created user information Secondly we need to modify user api rs by creating a handler that uses the get user method from the repository to get a user use crate models user model User repository mongodb repo MongoRepo use mongodb results InsertOneResult use rocket http Status serde json Json State post user data lt new user gt pub fn create user db amp State lt MongoRepo gt new user Json lt User gt gt Result lt Json lt InsertOneResult gt Status gt create user code goes here get user lt path gt pub fn get user db amp State lt MongoRepo gt path String gt Result lt Json lt User gt Status gt let id path if id is empty return Err Status BadRequest let user detail db get user amp id match user detail Ok user gt Ok Json user Err gt Err Status InternalServerError The snippet above does the following Uses the routing macro to specify HTTP method corresponding route and route parameterCreates a get user handler that takes in the db a type to the MongoRepo and a path for accessing route path as parameters Inside the handler we created an id variable to get the user s id get the user s details from the database using the db get user method We returned the correct response if the request was successful or error if any Finally we need to modify our application entry point main rs to include the get user handler by importing the handler and adding a new service for it mod api mod models mod repository macro use extern crate rocket use api user api create user get user import the handler here use repository mongodb repo MongoRepo launch fn rocket gt let db MongoRepo init rocket build manage db mount routes create user mount routes get user Edit a User EndpointTo edit a user we must first modify the mongodb repo rs file by adding an edit user method to the implementation block use std env extern crate dotenv use dotenv dotenv use mongodb bson extjson de Error oid ObjectId doc results InsertOneResult UpdateResult modify here sync Client Collection use crate models user model User pub struct MongoRepo col Collection lt User gt impl MongoRepo pub fn init gt Self init code goes here pub fn create user amp self new user User gt Result lt InsertOneResult Error gt create user code goes here pub fn get user amp self id amp String gt Result lt User Error gt get user code goes here pub fn update user amp self id amp String new user User gt Result lt UpdateResult Error gt let obj id ObjectId parse str id unwrap let filter doc id obj id let new doc doc set id new user id name new user name location new user location title new user title let updated doc self col update one filter new doc None ok expect Error updating user Ok updated doc The snippet above does the following Modifies the dependencies to include UpdateResultAdds an update user method that takes in a self id and new user parameters and returns the updated user detail or an error Inside the method we converted the id to an ObjectId created a filter variable to get the matching document we wanted to update and used the doc macro to update the document fields Then we use the self referencing the MongoRepo struct to access the update one function from the collection to update the user matching the filter specified and handle errors Finally we returned the updated user information Secondly we need to modify user api rs by creating a handler that uses the update user method from the repository to update a user use crate models user model User repository mongodb repo MongoRepo use mongodb bson oid ObjectId results InsertOneResult modify here use rocket http Status serde json Json State post user data lt new user gt pub fn create user db amp State lt MongoRepo gt new user Json lt User gt gt Result lt Json lt InsertOneResult gt Status gt create user code goes here get user lt path gt pub fn get user db amp State lt MongoRepo gt path String gt Result lt Json lt User gt Status gt get user code goes here put user lt path gt data lt new user gt pub fn update user db amp State lt MongoRepo gt path String new user Json lt User gt gt Result lt Json lt User gt Status gt let id path if id is empty return Err Status BadRequest let data User id Some ObjectId parse str amp id unwrap name new user name to owned location new user location to owned title new user title to owned let update result db update user amp id data match update result Ok update gt if update matched count let updated user info db get user amp id return match updated user info Ok user gt Ok Json user Err gt Err Status InternalServerError else return Err Status NotFound Err gt Err Status InternalServerError The snippet above does the following Modifies the dependencies to include ObjectIdUses the routing macro to specify HTTP method corresponding route route parameter and body dataCreates an update user handler that takes in the db a type to the MongoRepo path and new user as parameters Inside the handler we created an id variable to get the user s id update the user s details from the database using the db update user method by passing in the updated user s information Finally we checked if the update was successful and returned the updated user or error if any Finally we need to modify our application entry point main rs to include the update user handler by importing the handler and adding a new service for it mod api mod models mod repository macro use extern crate rocket use api user api create user get user update user import the handler here use repository mongodb repo MongoRepo launch fn rocket gt let db MongoRepo init rocket build manage db mount routes create user mount routes get user mount routes update user Delete a User EndpointTo delete a user we must first modify the mongodb repo rs file by adding an delete user method to the implementation block use std env extern crate dotenv use dotenv dotenv use mongodb bson extjson de Error oid ObjectId doc results InsertOneResult UpdateResult DeleteResult modify here sync Client Collection use crate models user model User pub struct MongoRepo col Collection lt User gt impl MongoRepo pub fn init gt Self init code goes here pub fn create user amp self new user User gt Result lt InsertOneResult Error gt create user code goes here pub fn get user amp self id amp String gt Result lt User Error gt get user code goes here pub fn update user amp self id amp String new user User gt Result lt UpdateResult Error gt update user code goes here pub fn delete user amp self id amp String gt Result lt DeleteResult Error gt let obj id ObjectId parse str id unwrap let filter doc id obj id let user detail self col delete one filter None ok expect Error deleting user Ok user detail The snippet above does the following Modifies the dependencies to include DeleteResultAdds a delete user method that takes in a self and id as parameters and returns the deleted user detail or an error Inside the method we converted the id to an ObjectId and created a filter variable to get the matching document we wanted to delete Then we use the self referencing the MongoRepo struct to access the delete one function from the collection to delete the user matching the filter specified and handle errors Finally we returned the deleted user information Secondly we need to modify user api rs by creating a handler that uses the delete user method from the repository to delete a user use crate models user model User repository mongodb repo MongoRepo use mongodb bson oid ObjectId results InsertOneResult modify here use rocket http Status serde json Json State post user data lt new user gt pub fn create user db amp State lt MongoRepo gt new user Json lt User gt gt Result lt Json lt InsertOneResult gt Status gt create user code goes here get user lt path gt pub fn get user db amp State lt MongoRepo gt path String gt Result lt Json lt User gt Status gt get user code goes here put user lt path gt data lt new user gt pub fn update user db amp State lt MongoRepo gt path String new user Json lt User gt gt Result lt Json lt User gt Status gt update user code goes here delete user lt path gt pub fn delete user db amp State lt MongoRepo gt path String gt Result lt Json lt amp str gt Status gt let id path if id is empty return Err Status BadRequest let result db delete user amp id match result Ok res gt if res deleted count return Ok Json User successfully deleted else return Err Status NotFound Err gt Err Status InternalServerError The snippet above does the following Uses the routing macro to specify HTTP method corresponding route and route parameterCreates a delete user handler that takes in the db a type to the MongoRepo and path as parameters Inside the handler we created an id variable to get the user s id and delete the user from the database using the db delete user method by passing in the id Finally we returned the appropriate response or error if any Finally we need to modify our application entry point main rs to include the delete user handler by importing the handler and adding a new service for it mod api mod models mod repository macro use extern crate rocket use api user api create user get user update user delete user import the handler here use repository mongodb repo MongoRepo launch fn rocket gt let db MongoRepo init rocket build manage db mount routes create user mount routes get user mount routes update user mount routes delete user Get all Users EndpointTo get the list of users we must first modify the mongodb repo rs file by adding a get all users method to the implementation block use std env extern crate dotenv use dotenv dotenv use mongodb bson extjson de Error oid ObjectId doc results InsertOneResult UpdateResult DeleteResult sync Client Collection use crate models user model User pub struct MongoRepo col Collection lt User gt impl MongoRepo pub fn init gt Self init code goes here pub fn create user amp self new user User gt Result lt InsertOneResult Error gt create user code goes here pub fn get user amp self id amp String gt Result lt User Error gt get user code goes here pub fn update user amp self id amp String new user User gt Result lt UpdateResult Error gt update user code goes here pub fn delete user amp self id amp String gt Result lt DeleteResult Error gt delete user code goes here pub fn get all users amp self gt Result lt Vec lt User gt Error gt let cursors self col find None None ok expect Error getting list of users let users cursors map doc doc unwrap collect Ok users The snippet above adds a get all users method that takes in a self as a parameter and returns the list of users or an error Inside the method we use the self referencing the MongoRepo struct to access the find function from the collection without any filter so that it can match all the documents inside the database and handle errors Finally we returned the list of users Secondly we need to modify user api rs by creating a handler that uses the get all users method from the repository to get list of users use crate models user model User repository mongodb repo MongoRepo use mongodb bson oid ObjectId results InsertOneResult use rocket http Status serde json Json State post user data lt new user gt pub fn create user db amp State lt MongoRepo gt new user Json lt User gt gt Result lt Json lt InsertOneResult gt Status gt create user code goes here get user lt path gt pub fn get user db amp State lt MongoRepo gt path String gt Result lt Json lt User gt Status gt get user code goes here put user lt path gt data lt new user gt pub fn update user db amp State lt MongoRepo gt path String new user Json lt User gt gt Result lt Json lt User gt Status gt update user code goes here delete user lt path gt pub fn delete user db amp State lt MongoRepo gt path String gt Result lt Json lt amp str gt Status gt delete user code goes here get users pub fn get all users db amp State lt MongoRepo gt gt Result lt Json lt Vec lt User gt gt Status gt let users db get all users match users Ok users gt Ok Json users Err gt Err Status InternalServerError The snippet above does the following Uses the routing macro to specify HTTP method and corresponding routeCreates a get all users handler that uses the db delete user method to get the list of users Then we returned the list of users or error if any Finally we need to modify our application entry point main rs to include the get all users handler by importing the handler and adding a new service for it mod api mod models mod repository macro use extern crate rocket use api user api create user get user update user delete user get all users import the handler here use repository mongodb repo MongoRepo launch fn rocket gt let db MongoRepo init rocket build manage db mount routes create user mount routes get user mount routes update user mount routes delete user mount routes get all users With that done we can test our application by running the command below in our terminal cargo run ConclusionThis post discussed how to modularize a Rust application build a REST API and persist our data using MongoDB You may find these resources helpful RocketMongoDB Rust DriverSerde Serializing and Deserializing library Rust Environment Loader 2022-05-26 12:31:23
Apple AppleInsider - Frontpage News Apple's iPhone emergency SOS saves woman from attempted rape https://appleinsider.com/articles/22/05/25/apples-iphone-emergency-sos-saves-woman-from-attempted-rape?utm_medium=rss Apple x s iPhone emergency SOS saves woman from attempted rapeAs years of a harrowing court case concluded with her attacker being sentenced to prison the survivor of a rape attempt has told how she used the iPhone emergency SOS to get help Apple s emergency SOS feature debuted in the Apple Watch in before coming to the iPhone with s iOS It s been credited with saving a snowboarder from a crevasse and now Virginia resident Kelli Worst has revealed how she used it to escape a rape attack This is something that will always be with me but I do feel like a survivor now more than a victim she told the local WAVY News Read more 2022-05-26 12:33:20
海外TECH Engadget Broadcom is buying VMware in a $61 billion mega-deal https://www.engadget.com/broadcom-buys-vmware-125814712.html?src=rss Broadcom is buying VMware in a billion mega dealBroadcom isn t done attempting major acquisitions The chip giant is buying cloud and virtualization focused software developer VMware for the equivalent of billion in cash and stock The move would fold Broadcom s software division into VMware and create a theoretical powerhouse that helps companies run apps in all sorts of environments including quot any quot cloud service The proposed union would have Broadcom take on billion of VMware s debt The deal should close sometime in Broadcom s fiscal no later than early calendar if regulators approve the deal Notably though VMware isn t yet locked into the merger ーa quot go shop quot clause will let it consider and even solicit deals from other companies through July th If the purchase goes forward it will represent one of the larger tech acquisitions so far Appropriately Dell whose founder sits on VMware s board set a record for several years when it bought VMware s then owner EMC for billion in Microsoft eclipsed that though with its still pending billion buyout of Activision Blizzard A play like this isn t completely unexpected On top of its debt VMware has seen declining profits and modest revenue gains This could help the firm overcome those hurdles and help its competitiveness Broadcom may not want to count on the purchase going through however Former President Trump blocked Broadcom s purchase of Qualcomm in over national security concerns While the administration and acquisition target are clearly different this time around it wouldn t be surprising if Broadcom faces similar levels of regulatory scrutiny 2022-05-26 12:58:14
海外TECH Engadget UK watchdog is investigating whether Google restricts competition in ads https://www.engadget.com/cma-google-ad-tech-investigation-122223972.html?src=rss UK watchdog is investigating whether Google restricts competition in adsThe UK s Competition and Markets Authority has launched a second investigation into Google s ad tech practices This probe in particular will look into the role Google plays in the quot ad tech stack quot or the set of services that facilitate the sale of online advertising space between advertisers and sellers like online content providers The organization explained that Google has strong positions at various levels of the ad tech stack and charges fees to both publishers and advertisers nbsp It s examining three key parts of the stack in which Google plays key roles since it owns the largest providers for each CMA will examine Google s practices for demand side platforms which give advertisers and media agencies a way to buy a publishers space for advertising from many sources It will also look into the company s practices relating to ad exchanges that can automate the sale of publishers inventory Finally the CMA will examine Google s publisher ad servers that manage a publisher s inventory to decide which ad to show at a given time based on the bids and direct deals for the space nbsp Google s practices ーif indeed questionable ーcould distort competition the CMA said It could contractually tie these various services together for instance so users won t have a choice but to go with Google all the way making it difficult for smaller rival services to compete nbsp According to Andrea Coscelli the CMA s Chief Executive quot Weakening competition in this area could reduce the ad revenues of publishers who may be forced to compromise the quality of their content to cut costs or put their content behind paywalls It may also be raising costs for advertisers which are passed on through higher prices for advertised goods and services quot The organization is also investigating whether Google and Meta colluded over ads That probe is all about digging into the advertising agreement between the two companies codenamed quot Jedi Blue quot and figuring out if that deal hinders competition in online advertising nbsp 2022-05-26 12:22:23
海外科学 NYT > Science Jimmy Carter Steps Into Fight Over Proposed Road in Alaska https://www.nytimes.com/2022/05/25/climate/alaska-anilca-wilderness-area.html president 2022-05-26 12:57:02
ニュース BBC News - Home Every household to get energy bill discounts of £400 this autumn https://www.bbc.co.uk/news/business-61583651?at_medium=RSS&at_campaign=KARANGA rishi 2022-05-26 12:33:18
ニュース BBC News - Home Cost of living: What Rishi Sunak's help means for you https://www.bbc.co.uk/news/business-61592496?at_medium=RSS&at_campaign=KARANGA support 2022-05-26 12:54:14
ニュース BBC News - Home Northern Ireland Protocol: Stormont recalled after Sinn Féin petition passes https://www.bbc.co.uk/news/uk-northern-ireland-61579659?at_medium=RSS&at_campaign=KARANGA ireland 2022-05-26 12:42:26
ニュース BBC News - Home Monkeypox: First case confirmed in Northern Ireland https://www.bbc.co.uk/news/uk-northern-ireland-61593051?at_medium=RSS&at_campaign=KARANGA irelandthere 2022-05-26 12:19:48
ニュース BBC News - Home Emily Bridges: Cyclist says transgender women are the 'punching bag' in society https://www.bbc.co.uk/sport/cycling/61563551?at_medium=RSS&at_campaign=KARANGA Emily Bridges Cyclist says transgender women are the x punching bag x in societyTransgender women are the current punching bag in society and are the targets of the culture war says cyclist Emily Bridges 2022-05-26 12:32:24
ニュース BBC News - Home Energy prices: How will the £5bn windfall tax work? https://www.bbc.co.uk/news/business-60295177?at_medium=RSS&at_campaign=KARANGA companies 2022-05-26 12:32:50
ニュース BBC News - Home What is the energy cap and why are energy prices going up? https://www.bbc.co.uk/news/business-58090533?at_medium=RSS&at_campaign=KARANGA bills 2022-05-26 12:53:59
ニュース BBC News - Home Which countries are doing the most to tackle energy bills? https://www.bbc.co.uk/news/61522123?at_medium=RSS&at_campaign=KARANGA bills 2022-05-26 12:15:18

コメント

このブログの人気の投稿

投稿時間:2021-06-17 05:05:34 RSSフィード2021-06-17 05:00 分まとめ(1274件)

投稿時間:2021-06-20 02:06:12 RSSフィード2021-06-20 02:00 分まとめ(3871件)

投稿時間:2020-12-01 09:41:49 RSSフィード2020-12-01 09:00 分まとめ(69件)