Share E-Book

Full-Stack Web Development with TypeScript 5 Craft modern full-stack projects with Bun, PostgreSQL, Svelte, TypeScript, and… (Mykyta Chernenko)(Z-Library)

Author

Rating No ratings yet

Log in to rate

TypeScript
Language English

Unleash the power of modern web development and master both frontend and backend development by building a real-world application Key Features Integrate AI capabilities in an application using the OpenAI API and learn AI-based features Build robust web applications with advanced TypeScript features like typing, generics, classes, and interfaces Implement user authentication and authorization mechanisms to protect your apps and user data Book Description This book takes you on a journey with TypeScript 5, introducing its nuances and advantages over traditional JavaScript, explaining TypeScript basics, and highlighting the syntax, typing, generics, classes, and interfaces. Expert advice will help you build your understanding of TypeScript's role in modern web applications. You'll gain hands-on experience with the tools required to write full-stack web applications end to end, beginning with setting up the Bun environment for backend development. This book also explores server-side functionality such as authentication, routing, and database integration with PostgreSQL. The second part of the book focuses on the integration of the OpenAI API, demonstrating the use of the GPT API for different use cases. The final part covers frontend development using Svelte, guiding you through UI design, state management, and performance optimization. Each chapter has real-world examples and comparisons to other technologies, providing you with a comprehensive understanding of full-stack development. By the end of this book, you'll have learned how to build modern web applications using TypeScript 5 and confidently tackle full-stack development challenges. Who this book is for This book is for junior to mid-level software engineers with foundational knowledge of JavaScript and web development, who are enthusiastic about the most cutting-edge technologies and want to expand their understanding of building full-stack applications end to end.

Format PDF
Size 2.5 MB
8
Views
(First 20 pages)

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

Page 1
(This page has no text content)
Page 2
Full-Stack Web Development with TypeScript 5 Craft modern full-stack projects with Bun, PostgreSQL, Svelte, TypeScript, and OpenAI Mykyta Chernenko
Page 3
Full-Stack Web Development with TypeScript 5 Copyright © 2024 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. The author acknowledges the use of cutting-edge AI, such as ChatGPT, with the sole aim of enhancing the language and clarity within the book, thereby ensuring a smooth reading experience for readers. It’s important to note that the content itself has been crafted by the author and edited by a professional publishing team. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. Group Product Manager: Kaustubh Manglurkar Publishing Product Manager: Bhavya Rao Book Project Manager: Sonam Pandey Senior Editor: Rashi Dubey Technical Editor: K Bimala Singha Copy Editor: Safis Editing Indexer: Subalakshmi Govindhan Production Designer: Vijay Kamble DevRel Marketing Coordinator: Nivedita Pandey and Anamika Singh First published: August 2024 Production reference: 1020724 Published by Packt Publishing Ltd. Grosvenor House 11 St Paul’s Square Birmingham B3 1RB, UK ISBN 978-1-83588-558-1 www.packtpub.com
Page 4
To my parents, Iryna and Vadym Chernenko; my aunt, Oksana Pidvalna; and my grandparents, Vira and Vasyl Pivdalni, for dedicating everything they could to help me reach where I am now, providing motivation and believing in me. To my wife, Yuliia, for her constant support, encouragement, and tremendous love throughout our life-long journey. – Mykyta Chernenko
Page 5
Foreword In the ever-evolving landscape of web development, mastering the latest technologies and integrating them seamlessly into full-stack projects is not just an advantage; it’s a necessity. Having worked alongside Mykyta Chernenko in various capacities—from frontline coding at Quantum to collaborating on a startup idea—I have witnessed firsthand his deep technical expertise and innovative approach to problem-solving in the tech world. Full-Stack Web Development with TypeScript 5 is Mykyta’s latest endeavor to empower full-stack developers by sharing his wealth of knowledge. This book is a beacon for junior and mid-level software engineers who are eager to dive deep into the intricacies of modern web development using an array of cutting-edge tools including TypeScript, Bun, PostgreSQL, Svelte, and the pioneering OpenAI API. What sets this book apart is not just its comprehensive coverage of both frontend and backend technologies but its practical, project-based approach. Through Mykyta’s guidance, you will not only learn the theoretical aspects of each technology but also aspects of how to apply some of them in real- world scenarios, crafting robust and scalable web applications. The journey from understanding basic concepts to integrating AI features is laid out with clarity and precision, ensuring that every reader comes away with the ability to navigate and innovate within the tech industry. As someone who has seen Mykyta’s meticulous approach to both writing and coding, I am confident that this book will serve as a great resource for those looking to make advancements in their careers. Whether it’s leveraging TypeScript’s capabilities to enhance application reliability or integrating AI to create dynamic user experiences, readers will find Full-Stack Web Development with TypeScript 5 an invaluable guide to becoming well-rounded, forward-thinking developers capable of tackling challenges for real business use cases. Embark on this learning journey with Mykyta, and equip yourself with the knowledge to not just participate in the future of tech but to shape it. Artem Korchunov Senior Software Engineer, Pillsorted
Page 6
Contributors About the author Mykyta Chernenko has over seven years of experience in technology, mainly in full-stack development with a focus on Python and TypeScript. He has also worked with Go, Kotlin, and Dart on various projects. His technical contributions include working on the Azure integration for Nutanix’s cluster discovery project and a key engineering role at Factmata, overseeing engineering and infrastructure. Currently, he holds a position as a senior consultant at KodeWorks. In addition to his technical work, Mykyta has mentored over 20 professionals, sharing his knowledge and experience. He is also the author of The Rational Software Engineer and runs a blog with the same name on Hackernoon, where he writes about his insights in the field. A big thank you to my best friend, Artem, for working closely with me, offering valuable feedback, and always being there both as a friend and a technical reviewer. I also want to express my gratitude to everyone at Packt Publishing for their professionalism and for making the publishing process seamless and positive. Your efforts have truly shaped this book.
Page 7
About the reviewers Kawtar Choubari is a software engineer specializing in JavaScript, TypeScript, React, and Next.js. She has been featured at Next.js Conf (2023) and React Conf (2024) with other community members and has spoken at major conferences, such as React Paris and Devoxx; she is passionate about sharing knowledge and making complex topics accessible. Also, Kawtar mentors students, guiding their tech careers, creates tech videos part-time, and shares her conference insights in a vlog format on her YouTube channel (under her name). Dedicated to educating, she conducts workshops and actively engages on social media platforms, sharing her expertise and extending her impact with the tech community. Kawtar’s work is encapsulated by these three words: engineering, educating, entertaining. Artem Korchunov is a product software engineer at Pillsorted, UK, where he blends a strong team- oriented approach with the ability to independently drive projects from inception to completion. Known for his project management and technical expertise in Terraform, AWS, .NET, and Node.js, Artem skillfully manages both the technical and business aspects of his work. I am grateful to the team at Pillsorted for their support and the rich, collaborative experiences that drive mutual growth and innovation. Joao Rodrigues is a senior typescript engineer at Acrontum Portugal.
Page 8
Preface xiii Part 1: Introduction to TypeScript 1 TypeScript Fundamentals 3 Technical requirements 4 Introduction to TypeScript and its evolution 5 Key differences between TypeScript and JavaScript 5 The advantages of using TypeScript in modern web development 6 Basic syntax of TypeScript 7 Simple types 7 Interfaces 8 Summary 9 2 TypeScript Deep Dive – Typing, Generics, Classes, and Interfaces 11 Technical requirements 11 Advanced typing techniques 12 Narrowing 12 null types 14 Function types 15 Creating types from other types 16 Utility types 16 Union types 17 Type intersections 19 Interface and OOP features 20 Interfaces 20 OOP functionalities 21 Generics 23 Promises 25 Summary 26 Table of Contents
Page 9
Table of Contentsviii Part 2: Backend Development with Bun and TypeScript 3 Configuring a Backend Environment with Bun and Hono 29 Technical requirements 30 Introducing Bun 30 Introducing Hono 31 Setting up the project 32 Adding linting and formatting 35 Adding middleware 37 Handling environment variables 39 Discussing the project structure 40 Summary 41 4 Building Backend Infrastructure with Bun, Hono, and TypeScript 43 Technical requirements 43 Implementing in-memory storage 44 Defining the interfaces 44 Creating database and API types 46 In-memory implementation of the interfaces 48 Implementing authentication and authorization 51 Developing the authentication middleware 51 Defining our controllers 54 Implementing chat controllers 56 Implementing the endpoints 56 Combining the endpoints 59 Using the index file for calling the function 61 Summary 63 5 Improving Reliability – Testing and Validation 65 Technical requirements 65 Writing validation with Zod 66 Adding validation to our authentication endpoints 66 Adding validation to our chat endpoints 68 Developing tests with Bun 70 Writing tests with Bun’s test runner 71 Writing tests for our authentication endpoints 72 Writing test for our chat endpoints 79 Summary 85
Page 10
Table of Contents ix 6 Advanced Backend Development – Security, Throttling, Caching, and Logging 87 Technical requirements 88 Managing security aspects 88 Adding request throttling 90 Writing the middleware 91 Implementing the middleware 92 Including the middleware in the main app 93 Managing the cache 94 Writing the cache middleware 94 Using the cache middleware in our chat endpoints 97 Using logging 99 Creating our logger’s configuration 99 Adding logger to our caching middleware 100 Summary 102 Part 3: Integrating PostgreSQL for Data Management 7 PostgreSQL Basics, Storage, and Setup 105 Technical requirements 105 Setting up PostgreSQL in Docker 106 What are Docker and Docker Compose? 106 What is PostgreSQL? 107 Creating a database as a Docker container 109 Constructing the database schema 111 Defining the database schema 112 Creating the database schema 114 Writing CRUD SQL operations 115 Summary 117 8 Interacting with PostgreSQL Using Libraries 119 Technical requirements 119 Integrating SQL implementation in the codebase 120 Writing a class 120 Updating a user 124 Incorporating SQL implementation into the main function 125 Replacing in-memory data storage with a SQL-based solution 126 Testing our SQL integrations to ensure reliability 128 Summary 129
Page 11
Table of Contentsx 9 Interacting with PostgreSQL Using Prisma ORM 131 Technical requirements 132 Introduction to ORMs and Prisma 132 Introducing Prisma – our ORM of choice 133 Understanding Prisma Migrate 133 Handling migrations using Prisma 134 Defining the database schema 134 Applying the migration to our database 136 Interacting with the database using Prisma 137 Defining the Prisma Client class 138 Integrating ORM into the main function 140 Testing our ORM integration 141 Summary 143 Part 4: AI Integration with OpenAI API 10 Basics of Integrating External APIs with TypeScript and Hono 147 Technical requirements 147 Introduction to API integration in TypeScript using fetch 148 Handling errors and retries 149 Validating API correctness 152 Summary 154 11 Setting Up and Configuring the OpenAI API for the Backend 155 Technical requirements 155 Introduction to LLMs and their applications 156 Setting up OpenAI API integration 158 Integrating the OpenAI API into our backend 159 Summary 162
Page 12
Table of Contents xi Part 5: Frontend Development with Svelte 12 Introduction to Svelte for Frontend Development 165 Technical requirements 165 What is Svelte? 165 History of Svelte 166 Differentiation from other frameworks 166 Learning Svelte fundamentals 167 Component composition structure 167 Introduction to .svelte file structure 167 Reactivity 169 Events 170 Bindings 172 Handling conditionals and iterating arrays 173 Props 174 Lifecycle 175 Stores 177 Summary 178 13 Setting Up the Svelte Project 179 Technical requirements 179 Discussing Vite and SvelteKit 179 Setting up the project 180 Exploring the project structure 180 Vite configuration file 181 TypeScript configuration file 181 Svelte configuration file 184 Configuring package.json 184 HTML entry point 186 Main file 187 Application title 187 Summary 188 14 Svelte Chat Application Development 189 Technical requirements 189 Writing routes for our application 190 Handling authentication logic 191 Defining the authentication store 191 Implementing Login component 194 Implementing Register component 198 Developing chat logic 201 Creating a parent component 201 Implementing the Header component 202 Creating the Chat component 203 Introducing styling 211 Writing application-wide styling 211
Page 13
Table of Contentsxii Styling for our Login and Register components 213 Styling our header component 216 Styling the chat container 217 Styling for the chat list 218 Styling our chat popup creation component 220 Styling for specific chats 221 Summary 223 15 Advanced Svelte Techniques 225 Technical requirements 225 Configuring formatting and linting 227 ESLint config file 227 Prettier file 229 Exploring a11y 230 The importance of accessibility 231 Accessibility rules and best practices in Svelte 231 Fixing accessibility issues in our project 231 Setting up i18n 233 Introducing testing 236 Configuring the Vite file 236 Exploring our setup file 237 Writing a test for our component 238 Further reading 242 Summary 242 Index 243 Other Books You May Enjoy 250
Page 14
Preface This book, Full-Stack Web Development with TypeScript 5, takes you on a journey into the robust and versatile world of TypeScript and will enable you to develop modern web applications from the ground up. With a focus on practical, real-world applications, this guide equips you with the necessary tools and techniques to master full-stack development using cutting-edge technologies such as Bun for the backend, Svelte for the frontend, PostgreSQL for database management, and the OpenAI API for AI integration. Whether you’re looking to deepen your existing knowledge or venture into new aspects of web development, this book provides step-by-step instructions and a project-based learning approach that culminates in the creation of a full-featured chat application. Who this book is for This book is designed for junior to mid-level software engineers who have a basic understanding of JavaScript and web development principles. It is especially beneficial for those looking to enhance their skills in modern web development technologies and application design, focusing on both frontend and backend development with TypeScript. What this book covers Chapter 1, TypeScript Fundamentals, introduces TypeScript, explaining its evolution from JavaScript and highlighting its fundamental syntax. This chapter lays the foundations for understanding how TypeScript enhances web development capabilities. Chapter 2, TypeScript Deep Dive – Typing, Generics, Classes, and Interfaces, explores advanced TypeScript features such as static typing, generics, and object-oriented programming concepts, which provide the tools we need to write more robust and maintainable code. Chapter 3, Configuring a Backend Environment with Bun and Hono, guides you through setting up Bun as a modern JavaScript runtime optimized for TypeScript, focusing on configuring the environment to enhance backend development. Chapter 4, Building Backend Infrastructure with Bun, Hono, and TypeScript, delves into creating a secure and efficient backend using Bun, Hono, and TypeScript, covering topics such as authentication systems, routing, and middleware integration.
Page 15
Prefacexiv Chapter 5, Improving Reliability – Testing and Validation, focuses on ensuring code quality and reliability in backend development, introducing techniques for data validation and testing strategies using Bun and TypeScript. Chapter 6, Advanced Backend Development – Security, Throttling, Caching, and Logging, covers critical backend aspects such as security measures, caching strategies, and best practices for debugging and logging to build scalable applications. Chapter 7, PostgreSQL Basics, Storage, and Setup, explores setting up a database using PostgreSQL within a Docker container to ensure reliable data persistence for web applications, detailing installation, schema construction, and CRUD operations. Chapter 8, Interacting with PostgreSQL Using Libraries, advances our backend infrastructure by incorporating SQL interactions directly into our server code using the pg library. This chapter discusses efficient and secure data handling, connection strategies, and the importance of testing SQL integrations to bolster application reliability. Chapter 9, Interacting with PostgreSQL Using Prisma ORM, transitions from direct SQL handling to using Object-Relational Mapping (ORM) for database interactions, focusing on using Prisma to streamline CRUD operations and manage schema migrations. This chapter covers how ORM integration can increase productivity, reduce errors, and make code clearer when working with PostgreSQL, as well as efficient migration management and testing ORM interactions. Chapter 10, Basics of Integrating External APIs with TypeScript and Hono, concludes our backend setup by teaching how to integrate APIs using fetch for robust communications in TypeScript. This chapter focuses on implementing reliable API calls, including error handling, retries, and response validation, to ensure effective and resilient external service interactions. Chapter 11, Setting Up and Configuring the OpenAI API for the Backend, details the process of integrating the OpenAI API into a TypeScript-based backend, focusing on configuration, security, and practical uses of AI models. Chapter 12, Introduction to Svelte for Frontend Development, introduces Svelte, a modern framework for building reactive user interfaces, and highlights its key features and benefits over traditional frameworks. Chapter 13, Setting up the Svelte Project, guides you through setting up a development environment for a Svelte-based application, exploring the configuration files and initial setup with tools such as Vite and SvelteKit. Chapter 14, Svelte Chat Application Development, walks through the development of a chat application using Svelte, covering frontend aspects such as routing, state management, and UI design. Chapter 15, Advanced Svelte Techniques, concludes the book with insights into maintaining and optimizing a Svelte and TypeScript application, covering testing, linting, accessibility, and internationalization strategies.
Page 16
Preface xv To get the most out of this book Before diving into this book, it is recommended that you have a solid foundation in JavaScript and basic web development concepts. Familiarity with the essentials of both frontend and backend development will help you understand and implement the advanced techniques covered in this guide. This book assumes knowledge of web application structure and design patterns and aims to enhance your skills through practical application and real-world examples. Software/hardware covered in the book Operating system requirements Bun 1.0 macOS or Linux TypeScript 5.2 Windows, MacOS, or Linux Hono 3.11 Windows, MacOS, or Linux Svelte 4.2 Windows, MacOS, or Linux Vite 5.0 Windows, MacOS, or Linux Eslint 8.57 Windows, MacOS, or Linux Svelte-routing 2.11 Windows, MacOS, or Linux Prisma 5.7 Windows, MacOS, or Linux Pg 8.11 Windows, MacOS, or Linux Zod 3.22 Windows, MacOS, or Linux Axios 1.6 Windows, MacOS, or Linux If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book’s GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code. If you execute the code on Windows, be aware that Bun is in experimental mode and the instructions provided in the terminal must be used in a bash-like environment. Download the example code files You can download the example code files for this book from GitHub at https://github.com/ PacktPublishing/Full-Stack-Web-Development-with-TypeScript-5. If there’s an update to the code, it will be updated in the GitHub repository. We also have other code bundles from our rich catalog of books and videos available at https:// github.com/PacktPublishing/. Check them out!
Page 17
Prefacexvi Conventions used There are a number of text conventions used throughout this book. Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: “For example, when [] is used in a numerical context, it is coerced to 0, and division of 4 to 0 results in Infinity. “ A block of code is set as follows: const numbers: Array<number> = [1, 2] const bigNumbers: number[] = [300, 400] When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold: export function createAuthApp( userResource: IDatabaseResource<DBUser, DBCreateUser>, authApp.post( REGISTER_ROUTE, zValidator("json", registerSchema), async (c) => { const { email, password, name } = c.req.valid("json"); Any command-line input or output is written as follows: $ npm install -g typescript Bold: Indicates a new term, an important word, or words that you see onscreen. For instance, words in menus or dialog boxes appear in bold. Here is an example: “Turn on Automatic ESlint config if it was turned off.” Tips or important notes Appear like this.
Page 18
Preface xvii Get in touch Feedback from our readers is always welcome. General feedback: If you have questions about any aspect of this book, email us at customercare@ packtpub.com and mention the book title in the subject of your message. Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata and fill in the form. Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at copyright@packt.com with a link to the material. If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com. Share Your Thoughts Once you’ve read Full-Stack Web Development with TypeScript 5, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback. Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.
Page 19
Prefacexviii Download a free PDF copy of this book Thanks for purchasing this book! Do you like to read on the go but are unable to carry your print books everywhere? Is your eBook purchase not compatible with the device of your choice? Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost. Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.  The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily Follow these simple steps to get the benefits: 1. Scan the QR code or visit the link below https://packt.link/free-ebook/9781835885581 2. Submit your proof of purchase 3. That’s it! We’ll send your free PDF and other benefits to your email directly
Page 20
Part 1: Introduction to TypeScript In this part, you will dive into the world of TypeScript, understanding its core principles and advanced features. This section sets a strong foundation in TypeScript, highlighting its evolution from JavaScript and demonstrating its power in enhancing code quality and maintainability for large-scale applications. You’ll learn the basics as well as more complex concepts, such as generics and object- oriented programming, that are essential for robust web development. This part includes the following chapters: • Chapter 1, TypeScript Fundamentals • Chapter 2, TypeScript Deep Dive – Typing, Generics, Classes, and Interfaces
The above is a preview of the first 20 pages. Register to read the complete e-book.

Recommended for You

Loading recommended books...
Failed to load, please try again later

Tip the Site

Scan the WeChat Pay or Alipay code to tip. No login required.

WeChat Pay
Alipay
← Back to List