#criticise my coding style
163 messages · Page 1 of 1 (latest)
// 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
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?
maybe pass the config in through a constructor?
i.e. new App(config)
and move class App to a different file
this'll allow you to test App more easily
env err constructs it
ifk why i would do thay
noted
yeah, you construct it and throw it away
as unknown as Config; is semi-dangerous. I'd personally use zod or write my own type-validator for the config
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
looks fine to me, dont forget to forward options too though or you'll lose out on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/Error#cause
this.stack = (new Error()).stack;
``` is this needed?
which is super useful for async code 'cause new Error("foo bar baz", { cause: originallyCaughtError })
it was once upon a time, not sure if it's still needed now
ah
i went to this style like a few days ago
im pretty noob at it
idk anything about it
tbh
class Er extends Error {
static { Object.defineProperty(this.prototype, "name", { value: "potato" }) }
}
might be better than setting .name dynamically
As of ES2019 this is no longer necessary, subclassing Error works correctly
i can delete that line entirely?
yeah, unless you're targeting like node12 or really old browsers
node12 is EOL so I wouldn't bother
People targetting IE:
oops this is wrong, should've been this.prototype
i dont understand this
setting this.name = "blah" in the constructor is extra work you don't need to do. Even the original Error constructor doesn't do that
error defines it's name on its prototype Error.prototype.name
SO
so you can too
class YourErrorClass extends Error {}
YourErrorClass.prototype.name = "override Error name"
the static { } is just shorthand for the above
class YourErrorClass extends Error {
static { this.prototype.name = "override Error name" }
}
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
WHERE DID THE STACK GO
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 = ...)
this looks so weird
can i make it log in a syntax i want
like
or use the logger
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"
biggest advantage of inheriting the constructor is you can do
try {
...
}
catch(e) {
throw new DBError("Unrecoverable operation", { cause: e })
}
oh
by passing in the cause the causing error will be included when it gets printed out in the console
that sex
very nice
throw new DBError("foo", { cause: new Error("bar") })
cause: e looked better
wanna rate my config type too
yeah but you wanted to try it out
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
yeah I wouldn't do it that way
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
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
and then use export const config = Config.safeParse(parse(cf)), this way you can get rid of the as unknown as Config;
well, I'll leave that up to you. ORMs have been a lot of pain
not Prisma, afaik it doesn't do joins
drizzle is so sexy
and drizzle-orm works with deno
but drizzle-kit doesn't
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
probably extends, or if controller is mostly just properties implements
but im clueless
@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
do i need to read everything else above to catch up?
i mean mainly yea
because its the parts where i use this package
and we have no idea whats causing the error.
could we start again like it's a new question then since that's a lot
okie dokie
up parts are unnecesary
db.link is triggering the error right?
probably.
comment it out and see if it runs
entire reason of this code is to run that single function
yeah but it helps narrow down where to look
its.probably in db.link
it didnt happen before i added that
yea it is in db.link
ok
i have a suspicion what is going on
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?
that worked?
yea that worked
wtf
how do iremove this table from my database now
this shi ugly as hell