Web Development with Clojure, 2Nd Edition.Pdf
Total Page:16
File Type:pdf, Size:1020Kb
Prepared exclusively for Bob Erb www.allitebooks.com Under Construction: The book you’re reading is still under development. As part of our Beta book program, we’re releasing this copy well before a normal book would be released. That way you’re able to get this content a couple of months before it’s available in finished form, and we’ll get feedback to make the book even better. The idea is that everyone wins! Be warned: The book has not had a full technical edit, so it will contain errors. ßIt has not been copyedited, so it will be full of typos, spelling mistakes, and the occasional creative piece of grammar. And there’s been no effort spent doing layout, so you’ll find bad page breaks, over-long code lines, incorrect hyphen- ation, and all the other ugly things that you wouldn’t expect to see in a finished book. It also doesn't have an index. We can’t be held liable if you use this book to try to create a spiffy application and you somehow end up with a strangely shaped farm implement instead. Despite all this, we think you’ll enjoy it! Download Updates: Throughout this process you’ll be able to get updated ebooks from your account at pragprog.com/my_account. When the book is com- plete, you’ll get the final version (and subsequent updates) from the same ad- dress. Send us your feedback: In the meantime, we’d appreciate you sending us your feedback on this book at pragprog.com/titles/dswdcloj2/errata, or by using the links at the bottom of each page. Thank you for being part of the Pragmatic community! Dave & Andy Prepared exclusively for Bob Erb www.allitebooks.com Web Development with Clojure, 2nd Edition Build Bulletproof Web Apps with Less Code Dmitri Sotnikov The Pragmatic Bookshelf Dallas, Texas • Raleigh, North Carolina Prepared exclusively for Bob Erb www.allitebooks.com Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and The Pragmatic Programmers, LLC was aware of a trademark claim, the designations have been printed in initial capital letters or in all capitals. The Pragmatic Starter Kit, The Pragmatic Programmer, Pragmatic Programming, Pragmatic Bookshelf, PragProg and the linking g device are trade- marks of The Pragmatic Programmers, LLC. Every precaution was taken in the preparation of this book. However, the publisher assumes no responsibility for errors or omissions, or for damages that may result from the use of information (including program listings) contained herein. Our Pragmatic courses, workshops, and other products can help you and your team create better software and have more fun. For more information, as well as the latest Pragmatic titles, please visit us at https://pragprog.com. For international rights, please contact [email protected]. Copyright © 2016 The Pragmatic Programmers, LLC. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form, or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior consent of the publisher. Printed in the United States of America. ISBN-13: 978-1-68050-082-0 Encoded using the finest acid-free high-entropy binary digits. Book version: B2.0—February 14, 2016 Prepared exclusively for Bob Erb www.allitebooks.com Contents Changes in the Beta Releases . vii Introduction . ix 1. Getting Your Feet Wet . 1 Set Up Your Environment 1 Build Your First Web App 3 Refine Your App 8 What You’ve Learned 23 2. Clojure Web Stack . 25 Route Requests with Ring 26 Extend Ring 32 Define the Routes with Compojure 35 What You’ve Learned 39 3. Luminus Architecture . 41 Manage the Project 41 Think in Terms of Application Components 43 HTML Templating using Selmer 51 What You’ve Learned 58 4. Add ClojureScript . 61 Understand ClojureScript 61 Configure ClojureScript Support 63 Add ClojureScript Support 63 Build the UI with Reagent 66 What You’ve Learned 79 Prepared exclusively for Bob Erb www.allitebooks.com Contents • iv 5. Real-time Messaging With Websockets . 81 Set Up Websockets on the Server 81 Make Websockets from ClojureScript 85 Websockets Using Sente 89 6. Writing RESTful Web Services . 97 Use Compojure-API 97 What You’ve Learned 113 7. Database Access . 115 Work with Relational Databases 115 Use Yesql 121 Generate Reports 124 What You’ve Learned 136 8. Picture Gallery . 137 The Development Process 137 What’s in a Gallery 138 Create the Application 140 Configure the Database 141 Task A: Account Registration 143 Task B: Login and Logout 162 Task C: Uploading Pictures 171 Task D: Displaying Pictures 180 Task E: Deleting Pictures 192 Task F: Account Deletion 195 Adding Some Color 199 9. Finishing Touches . 205 Unit Tests 205 Package the Application 211 What You’ve Learned 221 A1. Clojure Primer . 223 A Functional Perspective 223 Data Types 225 Using Functions 226 Anonymous Functions 227 Named Functions 227 Higher-Order Functions 229 Closures 230 Threading Expressions 231 Prepared exclusively for Bob Erb www.allitebooks.com Contents • v Being Lazy 232 Structuring the Code 232 Destructuring Data 233 Namespaces 235 Dynamic Variables 237 Polymorphism 237 What about Global State? 240 Writing Code That Writes Code for You 241 The Read-Evaluate-Print Loop 243 Calling Out to Java 243 Calling Methods 244 Summary 244 A2. Authentication with OAuth . 247 Why Use OAuth 247 A3. Document-Oriented Database Access . 253 Picking the Right Database 253 Using CouchDB 254 Using MongoDB 257 A4. Writing RESTful Web Services With Liberator . 261 Using Liberator 261 Defining Resources 262 Putting It All Together 267 A5. Leiningen Templates . 273 What’s in a Template 273 Prepared exclusively for Bob Erb www.allitebooks.com Changes in the Beta Releases Beta 2, February 14 • Examples have been updated to the latest version of the Luminus template. The source paths have been changed, and the Swagger examples now use the latest version of compojure-api. • Fixed typos and improved phrasing based on errata and beta reader feedback. • Additional explanations have been added for sections that were found confusing. • New appendix on using OAuth with Twitter. Beta 1, February 3 Prepared exclusively for Bob Erb www.allitebooks.com report erratum • discuss Introduction This book’s cover has a bonsai tree on it. I chose it to represent elegance and simplicity, as these qualities make Clojure such an attractive language. A good software project is like a bonsai. You have to meticulously craft it to take the shape you want, and the tool you use should make it a pleasant experience. I hope to convince you here that Clojure is that tool. What You Need This book is aimed at readers of all levels. While having some basic proficiency with functional programming will be helpful, it’s by no means required to follow the material in this book. If you’re not a Clojure user already, this book is a good starting point, as it focuses on applying the language to solve con- crete problems. This means we’ll focus on a small number of language features needed to build common web applications. Why Clojure? Clojure is a small language that has simplicity and correctness as its primary goals. Being a functional language, it emphasizes immutability and declarative programming. As you’ll see in this book, these features make it easy and idiomatic to write clean and correct code. There are many languages to choose from and as many opinions on what makes any one of them a good language. Some languages are simple but verbose. You’ve probably heard people say that verbosity really doesn’t matter, the argument being that when two languages are Turing complete, anything that can be written in one language can also be written in the other with a bit of extra code. I think that’s missing the point, however. The real question is not whether something can be expressed in principle. It’s how well the language maps to the problem being solved. One language will let you think in terms of your Prepared exclusively for Bob Erb www.allitebooks.com report erratum • discuss Introduction • x problem domain while another will force you to translate the problem to its constructs. The latter is often tedious and rarely enjoyable. You end up writing a lot of boilerplate code and constantly repeating yourself. There’s a certain amount of irony involved in having to write repetitive code. Other languages aren’t verbose and they provide many different tools for solving problems. Unfortunately, having many tools does not directly translate into higher productivity. The more features there are, the more things you have to keep in your head to work with the language effectively. With many languages I find myself constantly expending mental overhead thinking about all the different features and how they interact with one another. What matters to me in a language is whether I can use it without thinking about it. When a language is lacking in expressiveness I’m acutely aware that I’m writing code that I shouldn’t be. On the other hand, when a language has too many features I often feel overwhelmed or I get distracted playing with them. To make an analogy with mathematics, having a general formula that you can derive others from is better than having to memorize a whole bunch of formulas for specific problems. This is where Clojure comes in. It allows us to easily derive a solution to a particular problem from a small set of general patterns. All you need to become productive is to learn a few simple concepts and a bit of syntax.