#criticise my coding style

163 messages · Page 1 of 1 (latest)

unkempt adder
#

aa

#
// deno-lint-ignore-file
import { parse } from "https://deno.land/[email protected]/encoding/toml.ts";
import { Config } from "./src/types/mod.ts";
import nhttp from "https://deno.land/x/[email protected]/mod.ts";
import { Logger } from "./src/utils/logger.ts";
import { envErr } from "./src/utils/error.ts";

const cf = await Deno.readTextFile('./config.toml');
export const config = parse(cf) as unknown as Config;

if(!config.server.port) new envErr("Failed to read PORT From the config. Please check your config.");

class App {
    app;
    constructor() {
        this.app = nhttp();
        this.app.listen(config.server.port, () => {
            Logger.infoLog(`API Listening on -- ${config.server.port}.`);
        });
        this.app.get('/', () => {
            return { cat: 'meow welcome to evilbio api :3 https://discord.gg/aaaanoadversiting' }
        })
    }       


}

const api = new App();
#

bullying is allowed

jagged acorn
#
if(!config.server.port) new envErr("Failed to read PORT From the config. Please check your config.");

Are you not doing anything with that error? or the envErr constructor throws it?

lapis pumice
#

i.e. new App(config)

#

and move class App to a different file

#

this'll allow you to test App more easily

unkempt adder
unkempt adder
jagged acorn
lapis pumice
#

as unknown as Config; is semi-dangerous. I'd personally use zod or write my own type-validator for the config

unkempt adder
#
const GenericErr = (ErrName: string) => class extends Error {
    constructor(message: string) {
        super(message)
   
   
        this.name = ErrName
        this.stack = (new Error()).stack;
    }
}

export const envErr = GenericErr("Env Error");
export const dbErr = GenericErr("Database Error" )
#
export class Logger{
    static infoLog(message: string) {
        console.log(`[%cINFO%c]: ${message}`, "color: #8d78cc", "color: white");
    };

    static warningLog(message: string) {
        console.log(`[%cWARN%c]: ${message}`, "color: #ccb478", "color: white");
    };
};
#

logger

#

and error handler

jagged acorn
#
this.stack = (new Error()).stack;
``` is this needed?
lapis pumice
#

which is super useful for async code 'cause new Error("foo bar baz", { cause: originallyCaughtError })

lapis pumice
jagged acorn
#

ah

unkempt adder
#

i went to this style like a few days ago

#

im pretty noob at it

#

idk anything about it

#

tbh

lapis pumice
#
class Er extends Error { 
    static { Object.defineProperty(this.prototype, "name", { value: "potato" }) }
}

might be better than setting .name dynamically

unkempt adder
#

too much

#

for me

#

ill learn

#

slowly

lapis pumice
# jagged acorn ah

As of ES2019 this is no longer necessary, subclassing Error works correctly

unkempt adder
#

i can delete that line entirely?

lapis pumice
#

yeah, unless you're targeting like node12 or really old browsers

#

node12 is EOL so I wouldn't bother

jagged acorn
lapis pumice
lapis pumice
#

error defines it's name on its prototype Error.prototype.name

unkempt adder
#

SO

lapis pumice
#

so you can too

class YourErrorClass extends Error {}
YourErrorClass.prototype.name = "override Error name"
#

the static { } is just shorthand for the above

unkempt adder
#

how do you put the name

#

when you like

lapis pumice
#
class YourErrorClass extends Error {
    static { this.prototype.name = "override Error name" }
}
unkempt adder
#

EnvError()

#

how do you put the error

#

throw new EnvError()

lapis pumice
#

yeah just like that

const GenericErr = (ErrName: string) => class extends Error {
    static { Object.defineProperty(this.prototype, "name", { value: ErrName }) }
}

export const envErr = GenericErr("Env Error");
export const dbErr = GenericErr("Database Error" )

is equivalent to what you have above

unkempt adder
#

WHERE DID THE STACK GO

lapis pumice
#

the stack is taken care of for you by modern interpreters

#

as in the Error constructor does that automatically

#

(years ago it didn't used to, so people did this.stack = ...)

unkempt adder
#

this looks so weird

#

can i make it log in a syntax i want

#

like

#

or use the logger

lapis pumice
#

Oh?

#

Exceptions are different than logging

#

if you want to do logging, just use the logger. Exceptions are supposed to be fatal

#

as in "this operation cannot continue, here's why... bye"

unkempt adder
#

LOL

#

bro im still clueless on what ORM to use

lapis pumice
unkempt adder
#

oh

lapis pumice
#

by passing in the cause the causing error will be included when it gets printed out in the console

unkempt adder
#

that sex

lapis pumice
#

very nice

unkempt adder
#

let me see

#

how can i test that now

#

i don;'t have an orm set up

#

uhh

lapis pumice
#

throw new DBError("foo", { cause: new Error("bar") })

unkempt adder
#

cause: e looked better

lapis pumice
unkempt adder
#

wanna rate my config type too

lapis pumice
#

yeah but you wanted to try it out

unkempt adder
#

that defo looks sexier

#
export interface Config {
    discord: {
        client_secret?: string,
        client_id?: string,
        token?: string,
        redirect_uri?: string,
    },
    server: {
        port: number
    },
    db: {
        host: string,
        user: string,
        password: string,
        database: string,
        port: number,
    },
    other: {
        cookie_secret: string
    }
}
#

its a TOML

#
[discord]

[server]
    port = 3000

[db]
    host = ""
    user = "odd"
    password = "$"
    database = ""
    port = 5432
[other]
#

this error check is unneeded

#

this one

#

because in the config the port isn't optional

lapis pumice
#
import { z } from 'zod';

export const Config = z.object({
  discord: z.object({
    client_secret: z.string().optional(),
    client_id: z.string().optional(),
    token: z.string().optional(),
    redirect_uri: z.string().optional(),
  }),
  server: z.object({
    port: z.number()
  }),
  db: z.object({
    host: z.string(),
    user: z.string(),
    password: z.string(),
    database: z.string(),
    port: z.number(),
  }),
  other: z.object({
    cookie_secret: z.string()
  })
});

type Config = z.infer<typeof Config>;

write it out in a schema like zod

unkempt adder
#

thats zod

#

lol

#

ill add zod later on

#

dw

#

i just need to find a good ORM to use with this

#

i have everything ready, database, zod schemas, user schemas, even database schema

#

just need the orm to get started

lapis pumice
#

and then use export const config = Config.safeParse(parse(cf)), this way you can get rid of the as unknown as Config;

lapis pumice
unkempt adder
#

yea especially with Deno

#

drizzle ❌
prisma ❌

#

im clueless to be honest.

lapis pumice
#

not Prisma, afaik it doesn't do joins

unkempt adder
#

and drizzle-orm works with deno

#

but drizzle-kit doesn't

unkempt adder
#

hey @lapis pumice

#

would you do it like this

class controller {}
class userController extends controller {}
#

or just userController

#

and other controllers

#

alone

#

on their own

lapis pumice
#

probably extends, or if controller is mostly just properties implements

unkempt adder
#

@lilac dock

#
import { Model, DataTypes } from "https://deno.land/x/[email protected]/mod.ts";

export class Invite extends Model {
    static table = "invites";

    static fields = {
        id: { types: DataTypes.UUID, primaryKey: true },
        owner: DataTypes.UUID,
        registrant: DataTypes.UUID
    };
};

export class User extends Model {
    static table = "users";

    static defaults = {
        views: 0,
        permissions: 0
    }

    static fields = {
        id: { types: DataTypes.UUID, primaryKey: true },
        username: { unique: true, types: DataTypes.STRING },
        password: DataTypes.TEXT,
        avatar_url: DataTypes.TEXT,
        background_url: DataTypes.TEXT,
        permissions: DataTypes.INTEGER,
        bio: DataTypes.TEXT,
        song: DataTypes.TEXT,
        views: DataTypes.INTEGER 
    };
};

export class Link extends Model {
    static table = "links";

    static fields = {
        id: { types: DataTypes.UUID, primaryKey: true },
        name: { unique: true, types: DataTypes.STRING },
        link: DataTypes.TEXT,
        icon: DataTypes.TEXT,
        belongsTo: DataTypes.UUID
    };
};
#
import { parse } from "https://deno.land/[email protected]/encoding/toml.ts";
import { Config } from "./types/mod.ts";
import nhttp from "https://deno.land/x/[email protected]/mod.ts";
import { Logger } from "./utils/logger.ts";
import { envErr } from "./utils/error.ts";
import { Invite, User, Link } from "./utils/schema.ts";


const cf = await Deno.readTextFile('./config.toml');
export const config = parse(cf) as unknown as Config;

import { Database, MySQLConnector } from "https://deno.land/x/[email protected]/mod.ts"

const connector = new MySQLConnector({
  database: config.db.database,
  host: config.db.host,
  username: config.db.user,
  password: config.db.password,
});

  export const db = new Database(connector);

db.link([Invite, User, Link])

await db.sync({ drop: true });

#

here it is

#

my entire code

lilac dock
#

do i need to read everything else above to catch up?

unkempt adder
unkempt adder
#

because its the parts where i use this package

#

and we have no idea whats causing the error.

lilac dock
#

could we start again like it's a new question then since that's a lot

unkempt adder
#

what?

#

no not the up

#

just this 2 codeblocks

lilac dock
#

okie dokie

unkempt adder
#

up parts are unnecesary

lilac dock
#

db.link is triggering the error right?

unkempt adder
#

probably.

lilac dock
#

comment it out and see if it runs

unkempt adder
lilac dock
#

yeah but it helps narrow down where to look

unkempt adder
#

its.probably in db.link

#

it didnt happen before i added that

#

yea it is in db.link

lilac dock
#

ok so now try each model

#

individually

unkempt adder
#

ok

lilac dock
#

i have a suspicion what is going on

unkempt adder
#

all of them are errroring

#

yup

#

all of them

lilac dock
#

ok let's try a testing model

#
export class Foo extends Model {
  static table = "foo_test"
  static fields = {}
}
db.link([Foo])

start here, does it work?

unkempt adder
#

that worked?

#

yea that worked

#

wtf

#

how do iremove this table from my database now

#

this shi ugly as hell

lilac dock
#

DROP TABLE foo_test FROM evil

#

ok so what i suspect is going on

#

each of your models uses
id: { types: DataTypes.UUID, primaryKey: true },

#

but i think this might be a typo

#

'type'?

#

build up your test model until it stops working

unkempt adder
#

sh

#

HOLY

#

thank you