Build a REST API with Node.js, TypeScript & MongoDB

Bootstrap the application

yarn init 
npx typescript --init
yarn add express yup config cors express mongoose pino pino-pretty dayjs bcrypt jsonwebtoken lodash nanoid
yarn add @types/body-parser @types/config @types/cors @types/express @types/node @types/yup @types/pino @types/mongoose @types/bcrypt @types/jsonwebtoken @types/lodash @types/nanoid ts-node typescript -D
mkdir src && touch /src/app.ts
mkdir config && touch /config/default.ts
mkdir src/logger && touch src/logger/index.ts 
mkdir src/db && touch src/db/connect.ts

User registration

mkdir src/model && touch src/model/user.model.ts
mkdir src/service && touch src/service/user.service.ts
mkdir src/controller && touch src/controller/user.controller.ts
touch src/model/session.model.ts
touch src/service/session.service.ts
touch src/controller/session.controller.ts
app.post(“/api/users”, validateRequest(createUserSchema), createUserHandler);
mkdir src/middleware && touch validateRequest.ts
mkdir src/schema && touch src/schema/user.schema.ts 
app.post("/api/sessions", validateRequest(createUserSessionSchema), createUserSessionHandler);
app.delete(“/api/sessions”, requiresUser, invalidateUserSessionHandler);
touch src/middleware.index.ts
app.get(“/api/sessions”, requiresUser, getUserSessionsHandler);

Post CRUD operations

touch src/model/post.model.ts
touch src/service/post.service.ts
touch src/controller/post.controller.ts
app.post(“/api/posts”, [requiresUser, validateRequest(createPostSchema)], createPostHandler);
app.get(“/api/posts/:postId”, getPostHandler);
app.put(“/api/posts/:postId”, [requiresUser, validateRequest(updatePostSchema)], updatePostHandler);
app.delete(“/api/posts/:postId”, [requiresUser, validateRequest(deletePostSchema)], deletePostHandler);

I am a full stack JavaScript developer, living in Melbourne, Australia. My preferred stack is Mongoose, TypeScript, Node.js, React & GraphQL.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store