#development

1 messages ยท Page 178 of 1

quartz kindle
#

im figuring out how to compile tzdata myself

#

because most existing builds have major flaws for the api, they ignore/merge historical data from before 1970 timezones

#

which i need in the api

sharp geyser
#

I see

quartz kindle
#

the idiot lead maintainer thought that was a good idea

#

if you search for a date for example, in 1948 in stockholm, sweden

#

you get the timezone for berlin

#

which is stupid (and wrong)

real rose
#

highhighhighhighhigh

quartz kindle
#

but he says "we onlyguarantee accuracy starting from 1970, evertything before that is out of scope for this project"

#

dumbass

earnest phoenix
quartz kindle
sharp geyser
#

Okay so like tf is this

earnest phoenix
#

that view

quartz kindle
#

insert no hori bonk meme

sharp geyser
earnest phoenix
real rose
#

-b 1192795369193623673

gilded plankBOT
#

upvote michaelbyk103_18600#0 was successfully banned.

real rose
#

im sick of you already

quartz kindle
#

lel

surreal sage
#

is this sleepy nodejs or is this fucked up

#

ok so like

#

i think it just sets globals or something

#

dam

acoustic bough
#
interface CustomRequest extends Request {
    user: SomeType
}```
#

you canโ€™t just assign a variable to an object which isnโ€™t typed to hold that key

surreal sage
#
declare module 'express-serve-static-core' {
  interface Request extends AuthProps {} // Auth props is a type
}```
sharp geyser
#

Okay well uhm

#

I wouldn't do it that way tbh

sharp geyser
#

Its better to do it that way as you know for sure that it will show up on intellisense

#

Thats the way I always do it anyways

surreal sage
#

it works

#

so

sharp geyser
#

Okay then what was the issue

#

You made it seem like it wasn't working

sharp geyser
#

Also just hope you know that it only adds intellisense auto fill

#

Some people think differently EYES

surreal sage
#

yea

radiant kraken
#

this one lacks the declare module thing, i'm not sure if that's required or not for Intellisense

#

cc @sharp geyser

sharp geyser
#

jesus fucking christ

little plover
#

weird question should some one mind helping me with somthing

sharp geyser
radiant kraken
little plover
#

not sure if its bc it seems top.gg is down bit i keep getting a error code 500 the site will load but if i look up anything like a bot i need it just give me a 500code error

rocky barn
#

me too

little plover
acoustic bough
#

500 is internal server error so yes

sage bobcat
#

One message removed from a suspended account.

acoustic bough
#

site is down

little plover
#

oh ok

radiant kraken
#

i'm quite noob when it comes to typescript typings sorry onionpray

rocky barn
#

is that why some bots are down too?

little plover
#

im gussing so

acoustic bough
#

if the bots are coded bad, yes

little plover
#

half of my bots all the sudden stoped worked once the site went down then

radiant kraken
acoustic bough
sharp geyser
little plover
#

im using dino apply giveaway and a couple others

sharp geyser
#

for example when discord.js devs want to add their own things to the client and have auto correct for it they would

declare module 'discord.js' {
  export interface Client {
    someDevShit: Type
  }
}
radiant kraken
#

ooo icic thanks ts god onionpray

sharp geyser
#

you can even expand the library functionality iirc with declare module though I don't remember

#

I havent used ts in ages

radiant kraken
#

i'm not sure if that huge type alias is necessary or not but i hope it help devs so that they get the right keys KEKW

sharp geyser
#

760+ just from one type is crazy

#

Thank god you have that in a typings file and not in code

#

right?

radiant kraken
#

it used to be in code

sharp geyser
radiant kraken
sharp geyser
#

code go brrr

radiant kraken
sharp geyser
#

tbf I don't know everything about how declare module works either I just know its intended usage

#

It seems like declare module is really meant to be used in .d.ts files but I break that rule all the time

surreal sage
#

typescript

#

i built my project

#

it's in dist

#

with .js extensions

sharp geyser
#

yea?

surreal sage
#

the main script

#

imports /middleware/auth

#

note: no file extension

#

i run the main script

#

it errors, because it cant find /middleware/auth

sharp geyser
#

Can you not make multiple small messages and put more than 4 words into a sentence

surreal sage
#

nah ๐Ÿ™‚

sharp geyser
#

then have fun getting help, its annoying when you spam chat with your problem

#

๐Ÿ˜„

surreal sage
#

ok lemme make one message for ya

#

"import no workie :("

#

hollon

sharp geyser
#

"then fix the no workie" is my response

surreal sage
#

relative imports without file extensions aren't working

#
// tsconfig.json

{
  "compilerOptions": {
    "target": "ES2020",
    "lib": ["esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": false,
    "outDir": "dist",
    "baseUrl": "./src",
    "paths": {
      "@/*": ["./*"]
    }
  },
  "include": ["src"],
  "exclude": ["node_modules"]
}
sharp geyser
#

@radiant kraken

The declare module syntax in TypeScript is used to declare the shape or structure of an external module or library for which there are no TypeScript type definitions. It allows you to tell the TypeScript compiler about the existence of a module and provide type information for its components.
According to chat gpt trollface

radiant kraken
#

i dont trust chatgpt

sharp geyser
#

its correct though

#

thats generally what declare module is used for

#

you can do it with your own modules though as well

#

every ts file that exports something is considered a module iirc

#

so you can use declare module on your own files and just modify it in a d.ts file if need be or for some other reason idk

surreal sage
#

scrollin through node docs and found this

async function * generate() {
  yield 'a';
  await someLongRunningFn({ signal });
  yield 'b';
  yield 'c';
}

What's the * before generate()?
And to confirm, yield in promises basically trigger .then everytime? (What about await generate()?)
first .then is 'a'
second 'b'...

wheat mesa
#

that's the *

#

Similar to returning IEnumerable<T> in C#

surreal sage
#

interesting

quartz kindle
#

and guess what

#

generator functions are about 30% slower than making your own iterator pattern

#

lmao

#

well its been a few years since i tested them tbh

#

but js has a looong history of adding new/better ways of doing things that are slower than the old way of doing things

wheat mesa
#

I never understood why people complicated iterators so much

#

This is another one of those things that rust does very well

#

Ranges and iterators

surreal sage
#

i recently saw this shitcode

#
const obj = {}
const keys = Object.keys(obj)

for (let i in keys) {
  const value = obj[keys[i]]
}```
#

ok anyways i've got a little problem

#

i'm doing mongoose model work and I have a static function

#

(this is typescript btw)

#

and I want to return the model as document, I just don't know what to set the types to

surreal sage
#
export interface User {}

interface IUser extends User, Document {}

function stuff(): Promise<IUser>
#

but there's this entire shitheap of an error

#

Type 'Document<unknown, {}, FlatRecord<{}>' is not assignable to type 'IUser | null'.

#

then another alike

surreal sage
#

got it

sharp geyser
#
type IUser = User & Document

or smth like that

#

unless you are going to be adding stuff to the IUser interface

#

also can't remember if its & or |

radiant kraken
#

i feel like i'm writing php at this point

lament rock
#

& is weird

#

ts is weird

#

but very cool

#

Also, if you use the keyword type, the properties are shown in intellisense and depending on the Record's property count, it could be insane and with the keyword interface, it will just show the name of the interface

crystal wigeon
#

has anyone used aws sso?

#

i want to link an aws account from my web app

#

i checked sso but it looks too complicated

#

for no reason at all

sharp geyser
#

Welcome to AWS where everything takes a rocket engineer to use

eternal osprey
#

hey does anyone know how to fix this problem? I already enabled cors on my api but for some reason my site doesn't allow http requests back:

[blocked] The page at https://.. was not allowed to display insecure content from http://...
#

like do i need to go to my domain hoster and enable http requests as well or..?

#

the api itself (the http) is just locally hosted from my vps, so i am unsure if i can even add a https to it.

frail smelt
vivid fulcrum
#
The fix for mixed content is quite simple: Web developers need to ensure that every resource on their page is loaded over HTTPS. In practice, this can prove tricky, as modern websites often load several different resources from various places.
eternal osprey
#

fuckk

#

i am accessing my api from a secured environment

#

while m api isn't

vivid fulcrum
#

you can containerize your api so it only exposes itself onto localhost

#

use nginx with certbot and tunnel it to your api that's running on localhost

#

it's a tedious process but it works

eternal osprey
#

i mean i have a domain name

#

but i have no clue how to change my api that's currently runnng on my vps using express to my domain name

#

can i maybe change my dns to my vps ip? (my api is currently running using express)

vivid fulcrum
#

no

#

you need to configure nameservers on your vps, which provider are you using?

#

also if your domain name is already in use, you cannot use tsfeerhuysch.nl/api, but rather api.tsfeerhuysch.nl

#

for the subdomain, just add a new A record on your domain management dashboard

#

you would set NAME to api and point the ip address to your vps

#

you might still have to configure nameservers on your vps though

#

generally you should wait a few hours to see if the changes applied, DNS caching is a pain

#

there's also another approach with which you can technically achieve your api pointing to tsfeerhuysch.nl/api

#

with nginx

eternal osprey
#

it's my first time doing all this

#

my api still just runs locally on it's api. Idk what i am doing wrong

eternal osprey
#

i am sorry, it's an A record

#

i will just wait it out in the hope that the dns works

vivid fulcrum
#

it should clear up some confusion, the guide is thorough

proven lantern
#

can a bot input a command to another bot through discord?

deft wolf
#

Nope

#

It's not possible

proven lantern
#

mmkay so i'd need to make an API for the other bot if i want them to communicate

#

thanks

surreal sage
#

Is there a way to 'synchronize' my mongoose in runtime

I want to make a change to a document
The document is elsewhere in a socket (as socket.user), I want the change I just made here too

surreal sage
#
switch (condition) {
  case value:
    {
      // my mind goes from, na na na na
    }
    break;
}```
wheat mesa
#

What?

surreal sage
#

nothin

warm surge
#

I just love it says my mind goes from, na na na na

shut zenith
#

How much time i need to wait to the page of my bot get refreshed?

#

I changed the name of my bot and his photo

solemn latch
#

-refreshdata

gilded plankBOT
#

topgg Fetching Your New Bot Data

To fetch your bot's new name or avatar, please follow these steps:
topggDotRed Click the Refresh Data button in the sidebar on the right.
topggDotRed Click Edit on your bot page and then Save.

๐Ÿ’ก Please note: If it still doesn't seem to change, make sure you actually changed the bot's avatar / name on your Discord Developer Portal and not the application's icon / name.

shut zenith
solemn latch
#

Did you do both steps?

shut zenith
# solemn latch Did you do both steps?

Sorry, it has already been updated, although I did the 2 steps I did not realize that it could take 5-10 minutes to update, sorry for the inconvenience.

sharp geyser
#

@radiant kraken So before hand I was using once_lazy or whatever to make globals but idk if thats the proper method.

#

I want to have a global db connection variable that can be used anywhere in the application

radiant kraken
sharp geyser
#

How else would I share connection?

radiant kraken
#

can't you just store it in a struct

#

and use that struct everywhere

sharp geyser
#

wym?

#

Structs are a one off thing no?

radiant kraken
#

what is your app like

#

does it make use of async

sharp geyser
#

They get created then destroyed right after you are done using it

#

it is asynchrnous yea

#

its a actix-web app

#

oh wait

#

actix web allows you to share data across the app anyway iirc

#

๐Ÿ˜ญ

radiant kraken
#

yup

sharp geyser
#

I dont remember how to do it tho

#

gotta scrounge the docs

radiant kraken
sharp geyser
#

Oh yep

#

thats exactly it

#

I wonder

#

Can I just pass in my connection function but give the Data a type of PgConnection

radiant kraken
#

wdym

sharp geyser
#

like this:

    HttpServer::new(|| {
        App::new()
            .service(index)
            .app_data(actix_web::web::Data::<PgConnection>::(init_connection))
    })
        .bind("localhost:2053")?
        .run()
        .await
#

or is it Data::<TYPE>()

radiant kraken
sharp geyser
#

so it can take a type

#

nice

#
    HttpServer::new(|| {
        App::new()
            .service(index)
            .app_data(actix_web::web::Data::<PgConnection>::new(init_connection()))
    })
        .bind("localhost:2053")?
        .run()
        .await

so something like this then should work right?

radiant kraken
#

yup

sharp geyser
#

that try it and see method doesn't work rn

#

Haven't actually implemented anything

radiant kraken
#

implement something then

sharp geyser
#

Actually before that

#

How the hell am I going to create a postgres user from this rust app

#

Cause I am creating a user when they sign up

radiant kraken
#

i've never used postgres before

sharp geyser
#

Oh god @radiant kraken

#

I just realized

radiant kraken
#

what

sharp geyser
#

I have to do frontend for this project pepesob

radiant kraken
#

frontend aint that hard bud

sharp geyser
#

It will look ass!

radiant kraken
#

it wont

sharp geyser
#

trust me it will

#

@dense flame I will hire you to do my frontend for me 200$ a week mmLol

radiant kraken
#

or sayuri

sharp geyser
#

sayuri too expensive

radiant kraken
#

@civic scroll you free?

sharp geyser
#

on a budget here

radiant kraken
#

cosmic's nothing compared to sayuri

sharp geyser
#

not nice!

#

cosmic is amazing

radiant kraken
#

yeah true

sharp geyser
#

sayuri would add animations to literally everything

#

rip the roblox devs on their 200$ laptop

#

๐Ÿ˜ญ

radiant kraken
#

i use a $300 laptop and sayuri's websites run perfectly fine with barely any lag

#

i'm sure it's pretty well optimized poggythumbsup

sharp geyser
#

doing backend in rust is both annoying and fun

radiant kraken
#

i can help you out of the annoying parts

sharp geyser
#

I have to be careful with rust cause the ownership and borrower is quirky

#

Right now just trying to figure out the best way to make a user

#

time to bust out postman

#

somethin I haven't used in ages

radiant kraken
#

compared to things like C++

sharp geyser
#

very true

#

which is why I love C++ but hate its error messages

#

I've honestly been using rust more than c++ as of late tho

radiant kraken
#

very good

sharp geyser
#

I am just wondering if I should bother making my own mini orm built on sqlx

#

cause using just sqlx queries all the time without any structure is going to be aids

#

I think I can use serde with sqlx and parse the select data into readable/accessible data

#

I will worry bout that later tho

radiant kraken
#

maybe

#

anyway you should try frontend again with your project

sharp geyser
#

I will

#

I am just not sure what to use

radiant kraken
#

you can always ask for feedback

sharp geyser
#

might go with react tho

#

it will be most familiar

radiant kraken
#

react is good

sharp geyser
#

or Angular

radiant kraken
pale vessel
#

use yew as a practice

sharp geyser
#

the newest version of Angular was looking fucking sexy

#

what is yew

pale vessel
#

it's like rust react

radiant kraken
#

rust react

sharp geyser
#

EH?

radiant kraken
#

i've heard mixed opinions about it tho

sharp geyser
#

it uses wasm I assume then?

radiant kraken
#

yup

sharp geyser
#

yea idk how I feel about using yew

#

if ima be doing front end rather stick with what I know more of

radiant kraken
#

yup

sharp geyser
#

if I try and do smth new ima just stop the project and quite frankly I think mine is a rather smart idea

#

Make money off those roblox devs PepeEvil

radiant kraken
#

so what is your project about again

sharp geyser
#

Making an external database tool for roblox game devs

#

DataStores suck as proven by people expanding on datastores themselves

radiant kraken
#

roblox? .-.

sharp geyser
#

Yes

#

Roblox games have seen a skyrocket in the industry and are becomming very successful

#

and where there is success there is money

#

Why not skimp a few bucks off the top myself?

radiant kraken
#

kekw nice

#

so you're planning to make it paid

sharp geyser
#

Free for small games

#

Paid for anyone who needs more resources

#

This tool will be purely rest api as you can't do anything else really cause roblox only allows Http calls of Post and Get

#

I think they might allow you to do some custom ones

#

but I can't remember

radiant kraken
#

poggers

sharp geyser
#

Only thing I am worried about down the road is performance

#

but thats a problem for the future me :)

radiant kraken
#

since it's just a database i don't think it does really need that much frontend

sharp geyser
#

Its a roblox db service

#

it will be primarily frontend

radiant kraken
#

bruh

sharp geyser
#

I will have to end up making a database viewer

#

not everyone will know how to use tools like dbeaver to view their databases

#

ofc those who do can still choose to do so

#

they have a connection string, they just need their user + pass and the db name they want to connect to

#

or I can make a fool proof tutorial on how to use dbeaver trollface

radiant kraken
#

still doesnt sound that bad

#

good luck on it

sharp geyser
#

Thanks

#

I will be crying in sorrow while using rust to do this

radiant kraken
#

you wont be crying with my help though (hopefully) iara_hehe

civic scroll
radiant kraken
civic scroll
#

sure

#

i will tell you what i know

civic scroll
radiant kraken
sharp geyser
#

but roblox devs have potatoe pcs

radiant kraken
#

i have a potato pc and sayuri's websites run fine

civic scroll
#

not if i abuse css

#

and canvas

#

canvas can get quite performant with heavy animations

sharp geyser
#

i see

radiant kraken
civic scroll
sharp geyser
#

Well before I even add a frontend ima at least get sign up and login working

#

What should I use for auth tokens? I was planning on using UUID but idk if thats unique enough

radiant kraken
civic scroll
#

i'm not used to... render engines

#

what should i say...

#

ah

#

i'm used to declarative (state) animation rather than imperative animation

#

like i declare what state to transition to

#

for raw geometry manipulation, i will have to specify what to render every frame

sharp geyser
#

Wait

civic scroll
#

aka. doing the interpolation myself, which is pain

sharp geyser
#

Why am I bother signing up with user/pass

#

I will just use roblox oauth

#

I think that exists

radiant kraken
#

you render svgs

#

animated svgs

sharp geyser
#

@radiant kraken This is a thing?

#

I was playing around

#

and this seems valid

#

Its just dereferencing a reference and then making it a reference again no?

#

Nvm roblox oauth is useless

#

access token is only valid for 15m unless I immediately cache the information as soon as they login I can't fetch anything new (which I will likely need to do if I went this route)

#

actually nvm wont ever need new info as I can only really access the profile or so to say the profile is the only useful data roblox supplies

radiant kraken
#

what were you planning to do

#

it's usually used for conversion between rust references and raw pointers

sharp geyser
#

Oh nothing

#

I was just messing around

#

lol

radiant kraken
civic scroll
radiant kraken
#

plus you said that canvas is very performant so

civic scroll
#

it does

#

i think more about what i want, rather than how to do to reach what i want

sharp geyser
#

well great

#

for now I cant do anymore dev

#

my contabo vps is down

radiant kraken
#

rip

deft wolf
#

F

sharp geyser
#

Love it when has an unplanned maintenance

radiant kraken
sharp geyser
#

Refreshing every 15m is annoying

surreal sage
#

you don't have to

#

refresh tokens dont expire

#

at least tmk

smoky flume
#

?

surreal sage
sharp geyser
surreal sage
#

access token and refresh token are different

sharp geyser
#

Once an access token expires, you have to refresh it

surreal sage
#

you use the refresh token to gain an access token

#

access tokens usually expire

sharp geyser
#

The access token is what allows you to request data on behalf of a user

surreal sage
#

refresh tokens don't expire on roblox

#

i know how oauth works

#

roblox expires the access tokens, not the refresh tokens

sharp geyser
#

So if you constantly need information, having to refresh every 15m is annoying

#

:)

spark flint
#

only refresh when needed ๐Ÿ‘

surreal sage
spark flint
#

roblox oauth is just bad

surreal sage
#

no?

spark flint
#

like tokens limited to that short is just unneccesary

surreal sage
#

you update userdata when e.g. they log in

spark flint
#

yes, refresh when a new update is absolutely needed, and store the data where possible

#

otherwise ratelimits are your worst enemy

surreal sage
#

should be tbh

#

got a big site with lots of users logging in? no more! 5 logins per minute ๐Ÿ˜‡

#

it's often 2 requests at once for oauth (login)

#

getting the access & refresh token

#

then user info

spark flint
#

which is same for over 100 users

surreal sage
#

100 different users can authorize

#

i think that's the only limit

spark flint
surreal sage
#

yea

spark flint
#

yeah

surreal sage
#

D2?

#

D2 grid square

spark flint
#

im glad roblox oauth does exist tho

#

better for verification bots

surreal sage
#

bound to happen sometime

spark flint
#

neko atsume my beloved

spark flint
surreal sage
#

i have a gif like that somewhere

#

gotta scroll

spark flint
#

best part of the VR g ame is the close ups

spark flint
#

lmfao

#

cors my behated

surreal sage
#

i wish the default was a nice *

#

regarding cors

smoky flume
surreal sage
#

my firefox is acting up

surreal sage
#

diff localhost port doesn't load

#

this is firefox dev edition

#

on vivaldi it does load

surreal sage
#

i can connect just fine with postman

#

it's cors (cors that doesnt work on other browsers) or firefox

smoky flume
spark flint
#

unrelated but so many people set their DNS A records to 1.1.1.1

#

its funny

#

๐Ÿค“

#

chrome

#

because i've used it all my life and i really cba to migrate from it

surreal sage
#

switched from vivaldi (too buggy :() to firefox dev

spark flint
#

my school uses MS edge

surreal sage
#

ewww

spark flint
#

and blocks everything on it

#

can't even use inspect element

#

or screenshot

#

its not bad

#

its just annoying

surreal sage
#

no its microsoft

#

it sucks

spark flint
#

each tab is a new window on alt tab

surreal sage
#

anything michaelsoft sucks

#

michaelsoft binbows

#

name 1 thing

#

true

#

got me there

#

cracked ps

#

it honestly worked great

#

name 1 company: Apple

#

and binbows

smoky flume
#

@surreal sage can i know your bot name and serevr ??

surreal sage
#

i had many

spark flint
smoky flume
surreal sage
#

see5

#

fake

#

wtf

smoky flume
surreal sage
#

๐Ÿ”ฅ

#

how is there

#

4 open

#

help

#

oh thats forwarded ports

deft wolf
#

There is also one for FTP

spark flint
#

i also recommend thunder client

#

basically postman built in

sharp geyser
#

Sucks I dont use vscode

#

I used to use insomnia

#

but postman the goat

radiant kraken
#

@sharp geyser how's your web app been going

sharp geyser
#

@radiant kraken

error[E0277]: the trait bound `&PgConnection: Executor<'_>` is not satisfied
   --> src\routes\auth.rs:37:20
    |
37  |         .fetch_one(pool.get_ref())
    |          --------- ^^^^^^^^^^^^^^ the trait `Executor<'_>` is not implemented for `&PgConnection`
    |          |
    |          required by a bound introduced by this call
    |
    = help: the trait `Executor<'c>` is implemented for `&'c mut PgConnection`
    = note: `Executor<'_>` is implemented for `&mut PgConnection`, but not for `&PgConnection`
note: required by a bound in `QueryAs::<'q, DB, O, A>::fetch_one`
   --> C:\Users\dyeaaaronjr\.cargo\registry\src\index.crates.io-6f17d22bba15001f\sqlx-core-0.7.3\src\query_as.rs:140:17
    |
137 |     pub async fn fetch_one<'e, 'c: 'e, E>(self, executor: E) -> Result<O, Error>
    |                  --------- required by a bound in this associated function
...
140 |         E: 'e + Executor<'c, Database = DB>,
    |                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `QueryAs::<'q, DB, O, A>::fetch_one`
#

help

#

please

#

me no understand

wheat mesa
sharp geyser
#

Well I understand that much

#

but why

#

I dont really understand the error is saying

wheat mesa
#

The error is saying that the get_ref function is defined by the trait Executor, but Executor is not implemented on &PgConnection, it is only implemented on &mut PgConnection

frosty shuttle
#

What ur making

wheat mesa
#

So something like this ```rs
trait Executor {
fn get_ref(&mut self) -> Something;
}

impl Executor for PgConnection {
fn get_ref(&mut self) -> Something {} // Notice the &mut self here
}

#

(internally)

sharp geyser
#

I see

#

But wait

#

Am I to just use &mut PgConnection as my data type in the generics?

#
#[get("/login")]
pub async fn login(pool: Data<&mut PgConnection>, data: Json<UserLogin>, session: Session) -> impl Responder {
    let result = sqlx::query_as::<_, User>("SELECT * FROM users WHERE email = $1")
        .bind(&data.email)
        .fetch_one(pool.get_ref())
        .await;

    match result {
        Ok(user) => {



            Redirect::to("/").permanent()
        },
        Err(err) => {
            HttpResponse::BadRequest().json({
                ["successful"] = false;
                ["reason"] = err.to_string();
            })
        }
    }
}
wheat mesa
#

I guess?

#

Whatever works

sharp geyser
#

Alright I will try it

#
error[E0277]: the trait bound `&&mut PgConnection: Executor<'_>` is not satisfied
   --> src\routes\auth.rs:37:20
    |
37  |         .fetch_one(pool.get_ref())
    |          --------- ^^^^^^^^^^^^^^ the trait `Executor<'_>` is not implemented for `&&mut PgConnection`
    |          |
    |          required by a bound introduced by this call
    |
    = help: the trait `Executor<'c>` is implemented for `&'c mut PgConnection`
note: required by a bound in `QueryAs::<'q, DB, O, A>::fetch_one`
   --> C:\Users\dyeaaaronjr\.cargo\registry\src\index.crates.io-6f17d22bba15001f\sqlx-core-0.7.3\src\query_as.rs:140:17
    |
137 |     pub async fn fetch_one<'e, 'c: 'e, E>(self, executor: E) -> Result<O, Error>
    |                  --------- required by a bound in this associated function
...
140 |         E: 'e + Executor<'c, Database = DB>,
    |                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `QueryAs::<'q, DB, O, A>::fetch_one`

๐Ÿ’€

#

I am confusion

wheat mesa
#

uhhhh

#

oh wait

#

why are you doing .get_ref()?

#

Instead of .fetch_one(&mut pool)

sharp geyser
#

cause I didn't know that was a thing

#

๐Ÿ’€

wheat mesa
#

I mean you could technically do .get_ref_mut() and it's the equivalent but you should prefer using &mut Whatever

#

That's some pretty common rust syntax that you should get used to

sharp geyser
#
pub async fn login(mut pool: Data<PgConnection>, data: Json<UserLogin>, session: Session) -> impl Responder {
    let result = sqlx::query_as::<_, User>("SELECT * FROM users WHERE email = $1")
        .bind(&data.email)
        .fetch_one(&mut pool)
        .await;

so like that?

#

I made the pool param mutable cause it wont let me do it otherwise

wheat mesa
#

Close but not correct

#

Do pool: &mut Data<PgConnection>

#

Unless you absolutely have to own the pool connection

sharp geyser
#

I mean not really.

#

I dont see a reason why

wheat mesa
#

Usually you should always prefer borrowing over owning something unless you need ownership

sharp geyser
#

Well in this case I dont see why the connection should be owned here

#

So yea, that should work

#
error[E0277]: the trait bound `&mut Data<PgConnection>: Executor<'_>` is not satisfied
   --> src\routes\auth.rs:37:20
    |
37  |         .fetch_one(pool)
    |          --------- ^^^^ the trait `Executor<'_>` is not implemented for `&mut Data<PgConnection>`
    |          |
    |          required by a bound introduced by this call
    |
    = help: the following other types implement trait `Executor<'c>`:
              <&'c mut PgConnection as Executor<'c>>
              <&'c mut PgListener as Executor<'c>>
              <&'c mut AnyConnection as Executor<'c>>
              <&Pool<DB> as Executor<'p>>
note: required by a bound in `QueryAs::<'q, DB, O, A>::fetch_one`
   --> C:\Users\dyeaaaronjr\.cargo\registry\src\index.crates.io-6f17d22bba15001f\sqlx-core-0.7.3\src\query_as.rs:140:17
    |
137 |     pub async fn fetch_one<'e, 'c: 'e, E>(self, executor: E) -> Result<O, Error>
    |                  --------- required by a bound in this associated function
...
140 |         E: 'e + Executor<'c, Database = DB>,
    |                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `QueryAs::<'q, DB, O, A>::fetch_one`

Okay wth man, I get that it is not satisified but the rest of the error is what confuses me

wheat mesa
#

Again this is not correct

#

you need to be doing .fetch_one(&mut pool)

sharp geyser
#

but you said I was wrong

#

๐Ÿ˜ญ

sharp geyser
wheat mesa
#

Because you're not doing pool: &mut WhateverType

sharp geyser
#

I am though?

wheat mesa
#

Show me your full ode

sharp geyser
radiant kraken
#

pool is already a &mut, no?

#

so you're basically doing a &mut of a &mut

wheat mesa
#

no

radiant kraken
#

there's a difference between

fn thing(mut a: Type)
and
fn thing(a: &mut Type)

radiant kraken
#

let thing = &mut ... is a reference to a mutable variable, but the reference itself is not mutable

#

just pass in thing

wheat mesa
#

im like 99% sure that's not how it works

#

I'll test

#

mmmmmm

#

I see

radiant kraken
#
fn thing(a: &mut Type) { ... }

let mut x = ...;

thing(&mut x); // ok
let y = &mut x;
thing(y); // ok
thing(&mut y); // not ok

fn other(mut a: Type) { ... }

let mut a = ...;
other(a); // ok
other(&mut a); // not ok
sharp geyser
#

Even if I pass just pool it wouldnt work

wheat mesa
#

the libs you're using have complicated generics and lifetimes and shit so it's difficult to debug without actually doing it myself

radiant kraken
sharp geyser
radiant kraken
#

@sharp geyser try pool.into_inner()

sharp geyser
#

wth does that do

radiant kraken
sharp geyser
#

Okay

#

Roughly the same error

#

```error[E0277]: the trait bound Arc<PgConnection>: Executor<'_> is not satisfied
--> src\routes\auth.rs:37:20
|
37 | .fetch_one(pool.into_inner())
| --------- ^^^^^^^^^^^^^^^^^ the trait Executor<'_> is not implemented for Arc<PgConnection>
| |
| required by a bound introduced by this call
|
= help: the following other types implement trait Executor<'c>:
<&'c mut PgConnection as Executor<'c>>
<&'c mut PgListener as Executor<'c>>
<&'c mut AnyConnection as Executor<'c>>
<&Pool<DB> as Executor<'p>>
note: required by a bound in QueryAs::<'q, DB, O, A>::fetch_one
--> C:\Users\dyeaaaronjr.cargo\registry\src\index.crates.io-6f17d22bba15001f\sqlx-core-0.7.3\src\query_as.rs:140:17
|
137 | pub async fn fetch_one<'e, 'c: 'e, E>(self, executor: E) -> Result<O, Error>
| --------- required by a bound in this associated function
...
140 | E: 'e + Executor<'c, Database = DB>,
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in QueryAs::<'q, DB, O, A>::fetch_one

radiant kraken
#

into_inner() returns an Arc<PgConnection>, and that Arc can be converted to a &PgConnection

#

does the fetch_one() method supports a reference as the argument?

sharp geyser
#

Honestly these docs are confusing wtf is all those letters

radiant kraken
#

woah that's a lot of lifetimes

sharp geyser
#

are those all lifetimes?

radiant kraken
#

'e go brrrrr

#

yup

sharp geyser
#

I know nothing about lifetimes rn

radiant kraken
#

oh the PgConnection must be mut

#

@sharp geyser try this!

let mut pool_mut = pool.into_inner();

.fetch_one(pool_mut.get_mut().unwrap());
sharp geyser
#

What in the fuck

wheat mesa
#

this looks janky

#

never had to use something like this before

sharp geyser
#

I mean

#

get_mut doesnt even exist on pool_mut

wheat mesa
#

uh it should

sharp geyser
#

nope

#

there is as_mut

wheat mesa
#

should be implemented on all Arc<T>

radiant kraken
#

pool_mut is an Arc<PgConnection> yes?

sharp geyser
#

but nothing else

sharp geyser
#

but looking at the props provided get_mut is not one of em

#

and errors

radiant kraken
#

wth

#

try as_mut then

sharp geyser
#

No field `get_mut` in type `Arc<PgConnection, Global>` [E0609]

radiant kraken
wheat mesa
#

field??

#

you aren't using the method then lol

radiant kraken
#

OH

sharp geyser
#

error[E0599]: no method named `get_mut` found for struct `Arc<PgConnection>` in the current scope

radiant kraken
#

Arc::get_mut(&mut pool_mut);

#

then .unwrap() it

#

i am on my phone iara_why_sob

sharp geyser
#

Wait

#

Does rust have inheritence?

radiant kraken
#

no

sharp geyser
#

Can one struct extend the other?

#

๐Ÿ˜ญ

radiant kraken
#

yes

sharp geyser
#

?

#

is it no or yes

radiant kraken
#

it doesnt have an extends keyword

wheat mesa
#

it has "inheritance"

radiant kraken
#

but you can simulate inheritance

wheat mesa
#

but it's not designed to be used the same way as in OOP

#

"inheritance" is achieved using traits

sharp geyser
#

I mean it would suck to make another struct that is similar to another one with an extra field

wheat mesa
#

But dynamic dispatch is slow and should be avoided

wheat mesa
sharp geyser
#

guess I will just make a whole new struct

#

actually

#

nvm

wheat mesa
#

Rust has like Box<dyn Trait> which is more or less designed to be used for errors, not for inheritance

sharp geyser
#
#[derive(Serialize)]
struct SignupStatus {
    created: bool,
    time: i64,
    reason: Option<String>
}

I will just use this, and if there is no need to supply a reason it wont error yea :D

fleet storm
#

what's the problem?

wheat mesa
#

A lot of traditional OOP is avoided by rust because of performance reasons, dynamic dispatch is expensive and often times completely unnecessaru

wheat mesa
radiant kraken
#
use core::ops::Deref;

struct A {}
impl A {}

struct B<'a> {
  a: &'a A,
}

impl<'a> B<'a> {
  fn new(a: &'a A) -> Self {
    Self {
      a,
    }
  }
}

// the trick
impl Deref for B<'_> {
  type Target = A;

  fn deref(&self) -> &Self::Target {
    self.a
  }
}

let a = A {};
a.a_funcs();

let b = B::new(&a);
b.a_funcs();
b.b_funcs();

@misty.dev

#

ig this is inheritance

wheat mesa
#

that's uh

#

a jank trick

radiant kraken
#

you can store structs in each other

sharp geyser
#

What me no understand

radiant kraken
#

here's a less janky trick ```rs
use core::ops::Deref;

struct A {}
impl A {}

struct B {
a: A,
}

impl B {
fn new(a: A) -> Self {
Self {
a,
}
}
}

// the trick
impl Deref for B {
type Target = A;

fn deref(&self) -> &Self::Target {
&self.a
}
}

let a = A {};
a.a_funcs();

let b = B::new(a);
b.a_funcs();
b.b_funcs();

#

deref() lets you implicitly also use the reference inside B, which is A

sharp geyser
#

ima just avoid the thought of inheritice in rust

wheat mesa
#

"traditional" inheritance is more or less implemented like so ```rs
trait Pet {
fn speak(&self) -> String;
}

struct Cat {
some_field: String
}

struct Dog {
some_other_field: String
}

impl Pet for Cat {
// impl speak
}

impl Pet for Dog {
// impl speak
}

// Then, you can store stuff like so
let pets: Vec<Box<dyn Pet>> = vec![];
pets.push(Box::new(Cat { some_field: "Something".to_string() }));
pets.push(Box::new(Dog { some_other_field: "Something".to_string() }));

#

But this is super inefficient performance wise and will 99% of the time end up with borrow checker conflicts

#

So, composition over inheritance is really what rust tries to promote

radiant kraken
#

You would rarely use Box<dyn ...> tbh

#

Deref is way better, though it only limits to one Type

#

Deref is used in things like Arc<> and Box<>, so that you don't have to call into_inner() whenever you want to call methods of the inner variable

wheat mesa
#

I edited it, I should've said "traditional" inheritance

radiant kraken
#

@wheat mesa @sharp geyser here is the documentation for String, you could say that String inherits &str

#

because you can also use methods from &str in a String

wheat mesa
#

This is a special case though and I don't see this often

radiant kraken
#

it's used very often lol

#

though i recommend you play around with traits more often misty

#

you will see a lot of it everywhere

wheat mesa
#

Even operators are implemented as traits

#

Kinda funny

radiant kraken
#

it's an easy way to do operator overloading

#

making let res = my_struct + my_other_struct; possible

wheat mesa
#

and yet somehow with all this fancy operator overloading I still fucking hate adding strings together

radiant kraken
#

why

#

just .push_str or format! it

wheat mesa
#

I understand why, but it's still so annoying

radiant kraken
#

me when println!("{s}{s2}");

wheat mesa
#

I know but this isn't the use case

#

Lots more cases where this becomes annoying

radiant kraken
#

if you want to add a &str to the beginning of a String, you can do

second.insert_str(0, first);
#

i appreciate Rust's way of differentiating string slices with owned strings tho

wheat mesa
#

And yet this is still annoying because I should just be able to add them together without the hassle of calling special methods

radiant kraken
#

me when format!

wheat mesa
#

I should not need to use a macro to concatenate two strings

#

Every other language on the planet has figured it out

radiant kraken
#

besides Rust is not a very high-level language anyway

wheat mesa
#

Itโ€™s honestly my biggest complaint about rust

#

Which is probably a good thing considering itโ€™s a minor issue

radiant kraken
#

same goes for C++

wheat mesa
#

I suppose thatโ€™s true for some scenarios but I donโ€™t find myself using C strings super often anyways

radiant kraken
#

use Strings instead of &str then poggythumbsup

wheat mesa
#

I do most of the time

#

But adding a string literal with an owned string is annoying

#

Same goes for c++

radiant kraken
#

well either using a macro, a special method, or an overloaded operator is the most you can get out of these languages

#

it's not that bad

wheat mesa
#

I feel like with the trait system, these operators should be implemented by default

radiant kraken
#

wym?

#

you can't mutate a &str sdForgor

sharp geyser
#

I donโ€™t even know what traits are

#

Ill google it later

radiant kraken
#
trait Thing {
  fn do_thing(&self) -> i32;
  fn do_other_thing_default_impl(&self) -> i32 {
    69
  }
}

struct MyType { a: i32 }
impl Thing for MyType {
  fn do_thing(&self) -> i32 {
    self.a + 69
  }
}

let t = MyType { a: 5 };
println!("{}", t.do_thing());
println!("{}", t.do_other_thing_default_impl());
#

you can do

fn func<T>(input: &T) -> i32
where
  T: Thing,
{
  input.do_thing() + input.do_other_thing_default_impl()
}
#

(you can also do fn func<T: Thing>(input: &T) -> i32, which does the same thing)

sharp geyser
#

Whatโ€™s the benefit of using traits over just making functions normally

deft wolf
#

Thanks

radiant kraken
#

smh

sharp geyser
#

Then what is the difference between a struct and a trait?

#

Explaining a trait like an interface, but to me it seems structs are more like interfaces

humble mauve
#

Alles gut

radiant kraken
#

they are datatypes

#

just like classes

#

you can't store properties to a trait

earnest phoenix
#

how hard is it to get a bot to message all members an info pack about our service?

deft wolf
#

Not that hard

sage bobcat
#

One message removed from a suspended account.

#

One message removed from a suspended account.

#

One message removed from a suspended account.

deft wolf
#

But you can delay it

#

So it's not gonna spam API

earnest phoenix
earnest phoenix
#

not spam so to speak

#

like a guide and info

#

can i send here what i was thinking to see if thats doable, im not promoting ๐Ÿค™๐Ÿป

#

Something like this

#

With links to channels

deft wolf
#

Ratelimit is ratelimit, no matter what kind of message you send to the user, you have to be careful not to exceed it because discord will block your bot for some time. You definitely won't send it at once

lyric mountain
#

dmming every member is a great way of being flagged for spam

earnest phoenix
#

Im a noob at all this so I appreciate the help

lyric mountain
deft wolf
#

Automod moment

lyric mountain
earnest phoenix
spark flint
#

your bot will be marked as spam regardless of ratelimits

#

my bot, even tho its verified, got marked as spam by Discord for sending out too many welcome DMs to users

#

that was like 300 in a day

#

discord has a strict antispam when it comes to bots

#

so be careful

earnest phoenix
#

appreciate it guys

#

๐Ÿ™

#

might just leave it as the welcome set up and everyone else can figure it out NM_Kekw

#

how about a bot that kept a tally

#

say i imput - 2

#

and another person with the right role could +5

#

and it kept count in a channel

#

feel free to dm if anyone has any ideas, appreciate the help legends

#

im hoping 1 of the 2838 bot developers might have an idea , will pay

lyric mountain
#

wdym with tally?

#

like a score keeper?

earnest phoenix
#

like keep a count

#

yeah

lyric mountain
#

just save on the database the ID of the score message

earnest phoenix
#

but several ppl could use a command and imout their score for the day

lyric mountain
#

it can technically work if you use an update queue

#

like, the message update every X seconds (best to use minutes), whenever someone uses that command you modify the tracked message

#

idk how to explain this tho

earnest phoenix
#

they would update the score daily across 10 ppl and give an overall score + or minus

sharp geyser
#

rust has many keywords as well that donโ€™t make much sense to me

#

Such as impl

#

Iโ€™ve noticed it used in combination with structs and I think traits as well

radiant kraken
#

with this you can implement your own methods for structs (impl StructName) or implement other traits for your structs (impl Trait for StructName)

sharp geyser
#

๐Ÿค”

sharp geyser
#

Sounds to me traits arenโ€™t useful at all

#

Only thing I can see traits being used for is if multiple structs can have the same methods

#

But beyond that it seems rather pointless

radiant kraken
#

traits can be complex

#

traits can also have default implementations too

#

if you implement this, you can do for elem in your_struct { ... }

lyric mountain
#

that sounds a lot like interfaces, are they equivalent?

radiant kraken
#

thus, impl Trait for Struct

lyric mountain
#

wdym required properties?

radiant kraken
#

e.g require classes that implement such interface to have a specific attribute/property

lyric mountain
#

ah yes, I was using java interfaces as a reference, we dont have that either

#

dont know much about rust

wheat mesa
#

You can add methods onto structs that you didnโ€™t create yourself

#

Without the mess of extending things like in traditional OOP

earnest brook
#

Qucik question

deft wolf
#

That's not even a question

#

Even worse than "don't ask to ask"

harsh nova
sage bobcat
novel vault
#

Hi

lament rock
sage bobcat
radiant kraken
#

?

sage bobcat
#

One message removed from a suspended account.

#

One message removed from a suspended account.

#

One message removed from a suspended account.

lament rock
#

May I request service

lyric mountain
#

503 service unavailable

green kestrel
#

just finished generating 99 combinations of images to represent all possible professions, races and genders in my bots game.

realised I would need a way to allow already established players to set or change their gender now.

what a huge feature I'm exhausted, babysitting midjourney for hours.

#

trying to tell midjourney what an enslaved lesser orc looked like without hitting their nsfw filters (they really don't like the terms used in the prompt lol)

green kestrel
#

can you afford 99 photorealistic art pieces? and have them delivered same day? it would cost tens of thousands and take months.

#

the amount of images I have in this bot is staggering

#

many more than you can generate on their free trial

#

you're just frustrated that it's no longer only accessible to people who can afford to hire an artist, im through with paying someone a commission or using stock art

sage bobcat
radiant kraken
#

i can pay @civic scroll to make 99 art pieces for me mmLol

civic scroll
quaint rampart
#

anyone able to help me with this? i cant get the spotify card to align with the stuff above the spotify card im not too good w front end ๐Ÿ˜… also its not fully aligned vertically and i also want the stuff above the card to bne all the way to the left aligned with about me and i want the spotify card to be all the way aligned with the end of the line on the right

https://sourceb.in/4Tnq6BUmR6
https://sourceb.in/yhtzVNKurQ

excuse the aids of a css file

#

essentially i want it to look like this

#

and if spotify has display: hidden; i want it to still remain the same

solemn latch
#

Like this?

#

Some content wont load for me, as I dont have all the files

#

Op, I didn't see the part about hiding spotifys card

quaint rampart
#

exactly like that actually

#

and oh i didnt send it as a link hold on

solemn latch
#

I dont think i'll need the link.

quaint rampart
#

oh alrighty, what isnt loading then?

solemn latch
#

Oh just the images, nothing I need to play around with it.

#

lemme make a gist, and play around with it to make sure this is right.

I might spoonfeed a little here, but only because you seem to really be trying ^-^

quaint rampart
#

thank you, and i really have ๐Ÿฅฒ ive been trying to deal with this problem for almost 2 hours now

solemn latch
#

I'm still learning too, so playing around with this is good practice

quaint rampart
#

yeah i mean ive defintely learned alot so far with css just today alone with this site its defintely good practice BUT VERYYYYY IRRITATING

solemn latch
#

1000%

#

Have you played around with figma?

Using figma auto layouts helped me with learning flex.

quaint rampart
#

i have not actually but i think i should, i really wanna get into front end but everytime i attempt to i remember why i didnt last time ๐Ÿฅฒ

solemn latch
#

So, there's a small issue with what I'm giving you.

Without the spotify thing the heights change, just set the parent div to a min height above the spotify height(solving everything would make me feel bad, but I can help if you cant figure it out)

https://gist.github.com/Team-Woo/1d26cf45dcc3b398ef65fb071c573f36/revisions

I did delete a few things that looked un-needed, but wasn't sure how much you need for other things.

quaint rampart
#

alrighty thank you so much and i actually appreciate the challenge its the only way to learn. ill def try to fix it tmr since its getting late here and see what i can do! thank you so much for your help and ill keep you updated :D

#

thank you again for your help

neon leaf
green kestrel
green kestrel
#

"you hurt my feels now you must die" kekeke

green kestrel
#

i wanted to concentrate on the bot this time around, not websites, so ive used my old wordpress site and its theme, instead of spending weeks designing a new site. it does the job and has mighty seo

deft wolf
#

Understandable

green kestrel
#

i will need to do some custom web work when i roll out the premium sub

#

im still not going to use discord's monetization

deft wolf
#

The website itself is quite understandable and readable, I have no objections to that, but what really irritates me is the fact that at the very top there is such a nice background and below it there is no background, only these black bars

sharp geyser
#

@radiant kraken @wheat mesa so I have a struct that is for use when I am giving status information such as if something succeeded or failed, and if something succeeded I dont need a reason so I made that field an Option<String>, thing is when I go to use the struct and give the reason field a value that has the type String I get the whole type expected to be Option<String> but got String instead thing, should I use Option::from(value) or Some(value)

sharp geyser
#

Whatโ€™s so wrong with asking questions

#

Sorry if Iโ€™m inconveniencing you I wonโ€™t ask anymore

radiant kraken
#

since it gets to the basics in a simple manner

pale vessel
#

its fine misty i barely read the book either

#

i just asked my friend for stuff and read the rest of the docs

radiant kraken
#

i read the book until i got to the chapter that talks about lifetimes onesieKEKW

#

and then i quit from learning Rust for about a year

sharp geyser
#

I don't read the book simply because thats not how I learn

#

I can read it all day long but I won't remember or actually understand any of it

radiant kraken
#

oh alright

radiant kraken
pale vessel
#

by examples im guessing

#

which is the same for me

#

theres RBE, maybe he'd be interested in that

fast jungle
#

I learn by doing, as with most people I think

sharp geyser
#

I read the basics and go from there

#

Playing around with the language is more helpful then reading a book on how it works.

radiant kraken
#

honestly i used to do the same too

sharp geyser
#

It's what I have always done and it seems to work out.

radiant kraken
#

whenever i read docs i would just scroll down to the example codeblock

#

and read the passage before it

sharp geyser
#

I look at a lot of examples as well, but most of the time trying to do something and looking at the error to see what I did wrong then fix it is more helpful

#

Cause I learn what I did wrong, how to identify it, and how to fix it

radiant kraken
#

ah okay

#

Rust's rustc --explain <error_code> should be useful to you

sharp geyser
#

Did not know it was a thing

#

thanks for pointing that out

radiant kraken
#

it's at the bottom of almost every error stack onesieKEKW

sharp geyser
#

Honestly with rust I find myself spending more on structuring the data then actually coding ๐Ÿ˜ญ

radiant kraken
#

kekw

sharp geyser
#
use std::sync::Arc;
use actix_session::Session;
use actix_web::*;
use web::{Data, Json};
use sqlx::{Executor, PgConnection};
use serde::{Deserialize, Serialize};
use argon2::{self, Config, hash_encoded};
use chrono::offset;
use uuid::Uuid;


trait HttpResponder {
    fn get_time() -> i64 {
        offset::Local::now().timestamp()
    }
}


#[derive(Debug, sqlx::FromRow)]
struct User {
    id: i32,
    username: String,
    email: String,
    created_at: i64
}

#[derive(Serialize)]
struct HttpError {
    time: i64,
    reason: Option<String>
}


#[derive(Deserialize)]
struct UserSignup {
    email: String,
    username: String,
    password: String
}

#[derive(Deserialize)]
struct UserLogin {
    email: String,
    password: String,
}

#[get("/login")]
pub async fn login(pool: &mut Data<PgConnection>, data: Json<UserLogin>, session: Session) -> impl Responder {

    let mut pool_mut = pool.into_inner();
    let result = sqlx::query_as::<_, User>("SELECT * FROM users WHERE email = $1")
        .bind(&data.email)
        .fetch_one(Arc::get_mut(&mut pool_mut).unwrap())
        .await;

    match result {
        Ok(_) => {

        },
        Err(err) => {
            HttpResponse::BadRequest().json(HttpError {
                reason: Some(err.to_string()),
                time: HttpResponder::get_time()
            })
        }
    }
}

#[post("/signup")]
pub async fn signup(pool: &mut Data<PgConnection>, data: Json<UserSignup>) -> impl Responder {

    let salt = Uuid::new_v4().as_bytes();
    let config = Config::default();
    let hashed_pass = hash_encoded(&data.password.as_bytes(), salt, &config).unwrap();
    let result = sqlx::query_as::<_, User>("INSERT INTO users (username, email, password, created_at)")
        .bind(&data.username)
        .bind(&data.email)
        .bind(&hashed_pass)
        .bind(offset::Local::now().timestamp())
        .fetch_one(pool.into_inner())
        .await;

    match result {
        Ok(_) => {
            let create_user_role = format!("CREATE USER {} WITH PASSWORD '{}'", &data.username, &data.password);
            sqlx::query(&create_user_role).execute(pool.get_ref()).await?;

            HttpResponse::Created().json(HttpError {
                status: 201,
                time: HttpResponder::get_time()
            })
        },
        Err(err) => {
            HttpResponse::InternalServerError().json(HttpError {
                reason: Some(err.to_string()),
                time: HttpResponder::get_time()
            })
        }
    }
}

this looks so bad

#

๐Ÿ˜ญ

radiant kraken
sharp geyser
#

No god no

#

This is my auth file

radiant kraken
#

oh okay good

sharp geyser
#

First thing I learned how to do was make mod files

#

No way was I going to make a 4000+ line project

radiant kraken
sharp geyser
#

hm?

#

I orignally had it with HttpError cause that is the big place that I would be using it

#

but idk too much about traits and it seemed useless to do so if I wasn't going to be doing much else

radiant kraken
#

you should remove the HttpResponder trait and make get_time as a standalone fn

sharp geyser
#

I can yea

#

I plan on having multiple util functions so I might as well move it to a whole new file all together

radiant kraken
# sharp geyser but idk too much about traits and it seemed useless to do so if I wasn't going t...

this is a good example

pub trait Summary {
    fn summarize(&self) -> String;
}

pub struct NewsArticle {
    pub headline: String,
    pub location: String,
    pub author: String,
    pub content: String,
}

impl Summary for NewsArticle {
    fn summarize(&self) -> String {
        format!("{}, by {} ({})", self.headline, self.author, self.location)
    }
}

pub struct Tweet {
    pub username: String,
    pub content: String,
    pub reply: bool,
    pub retweet: bool,
}

impl Summary for Tweet {
    fn summarize(&self) -> String {
        format!("{}: {}", self.username, self.content)
    }
}

pub fn notify<T: Summary>(item: &T) {
    println!("Breaking news! {}", item.summarize());
}
sharp geyser
#

So dont actually implement the function in the trait just outline what it should look like?

radiant kraken
#

you can call notify with a &NewsArticle or &Tweet

sharp geyser
#

Gotcha

sharp geyser
#

Fuck the borrow checker man

#

I still don't understand how to avoid it

radiant kraken
#

@sharp geyser

#

those are default implementations so that you don't have to include it whenever you do impl MyTrait for MyStruct, doing so would override the default implementation

sharp geyser
#

I see

#

The borrow checker in rust makes me wanna jump off a bridge

radiant kraken
sharp geyser
#

I feel like using Arcs for the db stuff is not the best

radiant kraken
#

can you tell me the error?

sharp geyser
#

There has to be a better way

radiant kraken
#

Arcs (atomically reference counted types) are very useful when sharing data between async threads, especially between async/await code

sharp geyser
#

I see

#

bro

#

reading the shit off of the error explainer is more confusing then the error ngl

#

I get the value is freed and since its being borrowed thats bad

radiant kraken
#

send the error

sharp geyser
#
error[E0716]: temporary value dropped while borrowed
  --> src\routes\auth.rs:70:16
   |
70 |     let salt = Uuid::new_v4().as_bytes();
   |                ^^^^^^^^^^^^^^           - temporary value is freed at the end of this statement
   |                |
   |                creates a temporary value which is freed while still in use
71 |     let config = Config::default();
72 |     let hashed_pass = hash_encoded(&data.password.as_bytes(), salt, &config).unwrap();
   |                                                               ---- borrow later used here
   |
   = note: consider using a `let` binding to create a longer lived value
#

I understand the error

#

but clicking the error code (as you can in the ide terminal) and reading the page it takes you too is more confusing

radiant kraken
#
let uuid = Uuid::new_v4();
let salt = uuid.as_bytes();

.as_bytes() here doesn't consume (immediately drops it after being called) the Uuid type, so you can't use it in one line

sharp geyser
#

I see

#

So what exactly does consume mean here?

#

I thought once something reaches the end of the scope it is gone

radiant kraken
#
fn thing(consumed_value: i32) {
  // consumed_value drops after this function ends
}

let value = 5;
thing(value);
// you can't use value after this, because it's already dropped/no longer exists
// therefore it's 'consumed' by thing()

// borrowing is the same thing as referencing
fn thing(borrowed_value: &i32) {}

let value = 5;
thing(&value);
// you can still use value after calling thing()!
sharp geyser
#

Man I am actually bout to throw my pc, I am crying ๐Ÿ˜ญ

#

Why is async rust so fucking annoying

#

Also using postgres in rust

radiant kraken
#

btw i32s (or any primitive number type) cannot be consumed so it's actually fine to call thing(value);

#

but not for other things like Strings

sharp geyser
#

I see

#

Honestly tempted to start this project over from scratch

#

I've gotten too messy with it

#

and cleaning it up is going to be annoying

radiant kraken
#

because when you make a copy of it, it doesn't matter because the value doesn't change (not the same story for things like Strings, which have to point to a specific memory location)

radiant kraken
#

we all went there before

#

as you understand more you will constantly want to rewrite the entire thing

sharp geyser
#

Rust is the lang I prefer to use for this, but by golly is it so fucking annoying

radiant kraken
#

it's fine, i can always help you

sharp geyser
#

Honestly I think I am just overthinking the entire thing

#

I am trying to do multiple things at once

#

And I am also trying to make everything perfect and worrying too much about how it will work

radiant kraken
#

sameeee

#

this is basically one of the things preventing me from making any new projects onesieKEKW

#

that perfectionism

sharp geyser
#

Yea

#

Not to mention that I have grown to hate working on things by myself

#

I am more of a team player now KEKW

#

So doing shit by myself is a big reason I lose motivation

radiant kraken
#

you can always have me on the project iara_smug

sharp geyser
#

If you want to, i'd love the help

#

A lot of it has to do with my need to seek praise from people who use my services KEKW

#

I like making things that help people

radiant kraken
#

i tend to make libraries more than actual standalone applications

sharp geyser
#

on god

radiant kraken
#

maybe because they're simple in nature

sharp geyser
#

I used to do the same

#

but then I saw no one was using em

#

and got depressed

#

I will say though I had a guy add me years ago and ask me questions about a lib I made for tracker.gg

#

so that was kinda exciting

radiant kraken
#

my lib was featured on a reddit thread and stackoverflow post once ๐Ÿ˜ญ

sharp geyser
#

oh nice

radiant kraken
#

though it's only one guy saying it

olive tiger
#

when i can vote topggHurt

sharp geyser
#

hey all it takes is one guy

#

@radiant kraken honestly no idea why I am overthinking the database.

#

I myself am only going to be having a single model to hold user data, the rest will be them creating their own.

radiant kraken