#making class based router
294 messages · Page 1 of 1 (latest)
!screenshot
Rather than screenshots, please provide either code formatted as:
```ts
// code here
```
Or even better, as an example on the TypeScript playground that is as simple as possible and reproduces the issue. This makes it easier to help you and increases the chances of getting an answer.
you did not specify the type for the UserController parameter
usercontroller doesn't have a type
do i have to manually write a type for it?
everything has a type
what is usercontroller's type?
yes, otherwise TS can't check the types
damn
also use camelCase for the name of your parameters
also what would i wrote in constructor of UserController
you want to pass a class and instantiate it
can you paste your code in a playground?
im trying to make a class based Exxpress api
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
no, but it's fine, you can put all your classes in the same playground and omit the imports
Preview:```ts
import {Router} from "express"
import {PrismaClient, User} from "@prisma/client"
const prisma = new PrismaClient()
export default class UserController {
constructor() {}
static async getUsers(
req: Request,
res: Response
): Promise<User[]> {
const users: User[] = await pri
...```
u wanna see user type?
Preview:```ts
import express, {
Request,
Response,
Router,
NextFunction,
} from "express"
import {PrismaClient, User} from "@prisma/client"
const prisma = new PrismaClient()
export class UserController {
constructor() {}
static async getUsers(
req: Request,
res: Respo
...```
@clear folio
what for example?>
Using the typeof operator in type contexts.
-constructor(UserController: UserController, Request: Request, Response: Response)
+public constructor(userController: typeof UserController, request: Request, response: Response)
Request, Response
also access modified were missing
read
right, your static method is async
you need to await the result
however, you are inside of the constructor, so you can't
oh so
prisma asks for asynchronous
so basically
typeof means
this is the type of that
5 is the type of 5
because they both are integers
?
no
UserController is the type for an instance of the UserController class
typeof UserController is the type for the UserController class itself
so basically
UserController is a class
but typeof UserController is the type of UserController
read my 3 messages
ur saying im insided cnstructor tho
yes,
router.get("/users", userController.getUsers(request, response));
is inside
public constructor(userController: typeof UserController, request: Request, response: Response) {
this.userController = new userController()
router.get("/users", userController.getUsers(request, response));
}
move
router.get("/users", userController.getUsers(request, response));
to a separate method
then call that methods every time after calling the constructor for the UserRouter class
so instad of
class UserRouter {
private userController: UserController;
public constructor(userController: typeof UserController, request: Request, response: Response) {
this.userController = new userController()
router.get("/users", userController.getUsers(request, response));
}
}
const myRouter = new UserRouter(UserController, myRequest, myResponse);
have
class UserRouter {
private userController: UserController;
public constructor(userController: typeof UserController) {
this.userController = new userController()
}
public async init(userController: typeof UserController, request: Request, response: Response) {
router.get("/users", await userController.getUsers(request, response));
return this;
}
}
const myRouter = await new UserRouter(UserController)
.init(UserController, myRequest, myResponse);
am i able to put all of my routes in that
beeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeer
my dumbass was doing this
you just need
class UserRouter {
private userController: UserController;
public constructor(userController: typeof UserController) {
this.userController = new userController()
router.get("/users", userController.getUsers);
}
}
also, I don't know why you want to store an instance of the userController
this.userController = new userController() this line doesn't make much sense
also, why pass the UserController as parameter, since there is no inheritance possible because of the static methods
might as well use the class directly
like so
public constructor() {
router.get("/users", UserController.getUsers);
}
idk, most of the code you've shown so far doesn't make much sense
should read the express doc
wdym
this is what i was doing
this would error, since getusers is a method it needs () also request and response passed inside it
wdym "needs ()"?
that is how you pass a method in JS
you are not calling that method yourself
where do you pass the request and response
you are just passing it
router.get need 2 parameters
- the route (a
string) - a callback, a function to execute, that function will be called and passed the request and response
you can either provide the function direclty, with a lmbda (req, res) => {}
but you can also pass a reference to a different function or method that could be called
like UserController.getUsers
UserController.getUsers() would calle that function, UserController.getUsers is a reference to it, but not calling it
but please, have a look at the JS docs before trying to correct others
it needs request and response
like im coding the controller
if request doesn't come in
it'll throw error
also don't get it wrong im not correcting you we're just talking
tldr. you don't need to call UserController.getUsers, router.get will do it for you
@clear folio
will i be able to use that?
wdym?
what about registering this route
calling router.get registers the route
you pass the route and a handler
and the handler will be called by the router object when a route matches
no i n
so you need to pass a function as handler, not call a function
I don't get why you are writing classes
nothing you do requires classes
it makes the whole thing more complicated
i want it to be complicated
bro this is so weird
I mean, i'm not going to write the whole code for you 😅
i just need to pass the router
this is the last step
pass the router?
yeah
yes
thats what we did in module based
but that would mean extracting the router from UserRouter and creating a wrapper method in App just for use
that's a lot of duplicate code
lots of wrapper code
for no real added benefit

stop sending emojies and explain whatt u mean
alright alright
can you just send that piece of code with the App class?
@clear folio
!screenshot
Rather than screenshots, please provide either code formatted as:
```ts
// code here
```
Or even better, as an example on the TypeScript playground that is as simple as possible and reproduces the issue. This makes it easier to help you and increases the chances of getting an answer.
import dotenv from "dotenv";
import express, {Application, Request, Response} from "express";
import { EnvError } from "./error";
import UserRouter from "./routers/users";
import UserController from "./controllers/users";
class App {
private _app: Application
public constructor() {
this._app = express()
}
public start() {
dotenv.config();
const port = process.env.PORT;
const host = process.env.HOST;
const date = new Date();
const time = `${date.getHours()}:${date.getMinutes()}`;
if(!host || !port) throw new EnvError("Failed to read enviroment table.");
this._app.use("/user", )
this._app.listen(port, () => {
console.log(`${time} | [STARTUP]: Server is running at: http://${host}:${port}`)
});
}
}
export default App;
@quaint owl
Preview:ts import dotenv from "dotenv" import express, { Application, Request, Response, } from "express" import {EnvError} from "./error" import UserRouter from "./routers/users" import UserController from "./controlle ...
@topaz oracle here
yes
Preview:```ts
import dotenv from "dotenv"
import express, {
Application,
Request,
Response,
Router,
} from "express"
import {PrismaClient, User} from "@prisma/client"
declare interface User {}
///////////////////////
export class App {
private
...```
can u make a better class based rest api?
lol what
no, what you have here is already peak programming in term of class based REST API
this looks so clean
whats the difference between deno and t his though
it's just another runtime, like Node.js but different
thats ridiculous
your code's ridiculous
im gonna have to recode all this
yo what if
i make only
the controller class based
and what are you trying to achieve with that?
i mean
you could just say
UserController.getUsers()
and get the getUsers func
could also just have a file with a bunch of functions
and when importing that file, name it "UserController"
u couldn't just do
Usercontroller.getUsers() though
yes
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#namespace_import
import * as UserController from "./user-controller";
// [...]
router.get("/users", UserController.getUsers);
wtf
yes, you are
no?
class Foo {} // Foo is a class
const foo = new Foo(); // foo is an instance of Foo
now replace Foo by Request
what do i pass then
nothing
but please, if you don't understand something, go look up the related documentation
for express as well as for js
if i don't pass anything where does it get the request thats coming ftom
so the app creates the request object
app recieves a connection from a user?
and pass it to the router
app creates a request object?
wich pass it to your controller
will this app do that?
internally
I mean the express application object
(usually named "app")
@clear folio look
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
you don't need to create a requet yourself
is this right
the app recieves an incoming request from a browser, it passes it to the router you registered (using app.use) (not present in this example), which in turn calls the handler you registered (using .get)
yes
the handler (a function) recieves the request object
app.get('/', (req, res) => {
res.send('Hello World!')
})
like, you are passing 2 parameters
the path for the handler
and the handler itself (a function)
and that function will be called when a request arrives for that path
you don't need to createand pass a request
then what the hell is this
just create your express app, your express router, and register routes
what are the types for the UserController?
in the UserController, there is the getUsers method, what are its types?
right, this is wrong
you need to import Request and Response from express in your UserController file
yeah, it's not the right Response class
it's another one with the same name
the this._app.get("/", )?
it's relative paths
its not working

