Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Kraus
Jan 17, 2008

Thanks!

I was having a conversation with a coworker yesterday where we got on the topic of what the smallest possible JS program is. We agreed that the program has to 'do something', as vague as that is. We figured that j=1 is probably the smallest program. Is there any smaller meaningful combination of characters in JS?

Adbot
ADBOT LOVES YOU

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Kraus posted:

Thanks!

I was having a conversation with a coworker yesterday where we got on the topic of what the smallest possible JS program is. We agreed that the program has to 'do something', as vague as that is. We figured that j=1 is probably the smallest program. Is there any smaller meaningful combination of characters in JS?

!0

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
j=1 doesn't do anything.

According to thefreedictionary.com a program is "(Computer Science) a sequence of coded instructions fed into a computer, enabling it to perform specified logical and arithmetical operations on data" but j=1 isn't performing any logical or arithmetical operations it's just assigning something to memory.

Lets not get metaphysical here guys.

Volguus
Mar 3, 2009
https://www.muppetlabs.com/~breadbox/software/tiny/teensy.html

reversefungi
Nov 27, 2003

Master of the high hat!
Anyone here experienced with Apollo Server? I'm trying to fix up the auth for one of our services, but for some reason, when using express, adding something to the request object in some custom middleware doesn't affect the req object in the context configuration when setting up the apollo server. Ideas? Here is a rough example of the code I have:

JavaScript code:
const app = express()

// have also tried app.get('/graphql'), app.all('*'), etc.
app.use((req, res, next) => {
    req.token = doStuffToGetToken()

    next()
})

function createServer(){
    const server = new ApolloServer({
        schema,
        context: ({ req }) => {
            console.log(req.token) // undefined <- why???
        }
    })
      
    server.applyMiddleware({
        app
    })

    app.listen(
        {
            port: GRAPHQL_PORT
        },
        () => console.log(`The GraphQL server is running on port ${GRAPHQL_PORT}`)
    )
}


connectToMongo(createServer)
I tried moving all the app instantiation logic inside the createServer function in case the closure was causing some issue, but no dice.

I found this article where someone more or less is doing the same thing so I assume that this would work, but for some reason the req object just doesn't seem to carry over in any meaningful way. I also can't use session storage, because the request/response objects in context don't seem to receive the middleware that has been applied to the main express app. Any ideas? I feel like I'm missing something obvious.

Edit: Also if I simple change doStuffToGetToken() to a string literal it still doesn't work, so there's definitely nothing wrong with the function itself.

reversefungi fucked around with this message at 23:42 on Sep 10, 2019

roomforthetuna
Mar 22, 2005

I don't need to know anything about virii! My CUSTOM PROGRAM keeps me protected! It's not like they'll try to come in through the Internet or something!
Or an even smaller program, !0

Kraus
Jan 17, 2008

Nolgthorn posted:

j=1 doesn't do anything.

According to thefreedictionary.com a program is "(Computer Science) a sequence of coded instructions fed into a computer, enabling it to perform specified logical and arithmetical operations on data" but j=1 isn't performing any logical or arithmetical operations it's just assigning something to memory.

Lets not get metaphysical here guys.

Well, we also figured that if "do something" meant output, the smallest you could get was: alert`` , which I mentioned above.

IAmKale
Jun 7, 2007

やらないか

Fun Shoe

The Dark Wind posted:

Anyone here experienced with Apollo Server? I'm trying to fix up the auth for one of our services, but for some reason, when using express, adding something to the request object in some custom middleware doesn't affect the req object in the context configuration when setting up the apollo server. Ideas? Here is a rough example of the code I have:

JavaScript code:
const app = express()

// have also tried app.get('/graphql'), app.all('*'), etc.
app.use((req, res, next) => {
    req.token = doStuffToGetToken()

    next()
})

function createServer(){
    const server = new ApolloServer({
        schema,
        context: ({ req }) => {
            console.log(req.token) // undefined <- why???
        }
    })
      
    server.applyMiddleware({
        app
    })

    app.listen(
        {
            port: GRAPHQL_PORT
        },
        () => console.log(`The GraphQL server is running on port ${GRAPHQL_PORT}`)
    )
}


connectToMongo(createServer)
I tried moving all the app instantiation logic inside the createServer function in case the closure was causing some issue, but no dice.

I found this article where someone more or less is doing the same thing so I assume that this would work, but for some reason the req object just doesn't seem to carry over in any meaningful way. I also can't use session storage, because the request/response objects in context don't seem to receive the middleware that has been applied to the main express app. Any ideas? I feel like I'm missing something obvious.

Edit: Also if I simple change doStuffToGetToken() to a string literal it still doesn't work, so there's definitely nothing wrong with the function itself.

The issue is that you're trying to make GraphQL requests without understanding how those requests are made. To keep things simple for now, I recommend that if you're using a GraphQL server, then you should always use a GraphQL client to make requests.

In your case, I highly recommend you stick with Apollo and use Apollo Client to make your API requests. The section of the docs on authentication, that will help populate req.token in your context() method, is here: https://www.apollographql.com/docs/react/recipes/authentication/

Happy Thread
Jul 10, 2005

by Fluffdaddy
Plaster Town Cop
How do I make documentation for my JavaScript library that is pretty? Like the MDN web docs that explain JavaScript's built-in functions?

I see tools like JSDoc but they seem more geared towards short automated descriptions instead of the long explanatory paragraphs found on MDN, mainly because any text has to be in the source code itself along with a bunch of markup added to generate the documentation. I understand how it could be useful to have code comments and documentation that automatically stays in sync like JSDoc offers, but I would rather have my code comments merely be links to the documentation pages where a longer and much more human-friendly description is made of each function.

Happy Thread fucked around with this message at 18:24 on Sep 16, 2019

The Fool
Oct 16, 2003


Maybe gitbook?

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
Why do service workers define self?

I tried to google it, but google is useless for precise techical questions.

Bruegels Fuckbooks
Sep 14, 2004

Now, listen - I know the two of you are very different from each other in a lot of ways, but you have to understand that as far as Grandpa's concerned, you're both pieces of shit! Yeah. I can prove it mathematically.

Wheany posted:

Why do service workers define self?

I tried to google it, but google is useless for precise techical questions.

self refers to the global execution context. (https://developer.mozilla.org/en-US/docs/Web/API/Window/self)
e.g. in a window, self returns the window. in a worker or a service worker, it is defined as the execution context of the worker/service worker.

the spec indicates that the global execution context of service worker is ServiceWorkerGlobalScope (https://w3c.github.io/ServiceWorker/#serviceworkerglobalscope-interface).

roomforthetuna
Mar 22, 2005

I don't need to know anything about virii! My CUSTOM PROGRAM keeps me protected! It's not like they'll try to come in through the Internet or something!

Wheany posted:

Why do service workers define self?
The capitalist's eternal question.

Ape Fist
Feb 23, 2007

Nowadays, you can do anything that you want; anal, oral, fisting, but you need to be wearing gloves, condoms, protection.

roomforthetuna posted:

The capitalist's eternal question.

Heyooooo

TheIncredulousHulk
Sep 3, 2012

I'm attempting to write a messenger web app mainly for a portfolio piece in which the conceit is that it doesn't require registration and functions more like a burner phone(you're randomly assigned a 10-digit id when you start and you can clear it and get a new one whenever, and messages automatically decay and/or get removed from conversation partners' devices when one of the participants tells it to)

All the messaging functionality works fine now but in order for any of the other security measures to matter I need to actually encrypt the message contents and I don't really have much of an idea how since I've only been coding for ~10 months. I've used Bcrypt for passwords before but that process doesn't really work when you've got to be able to decrypt messages from someone else besides yourself, right? Is there any crypto library in particular that anybody would recommend for this? Stack for it is React/Redux/Node Express/Mongo

Ola
Jul 19, 2004

TheIncredulousHulk posted:

I've used Bcrypt for passwords before but that process doesn't really work when you've got to be able to decrypt messages from someone else besides yourself, right?

That's right. Bcrypt isn't an encryption algorithm, but a hash algorithm. It changes a password to a hash, i.e. a string of gibberish, the same string of gibberish every time (with the same settings and same input) and with no way of finding out what the password was even if you know the settings and the gibberish.

I don't know which library to recommend, perhaps this is good: https://github.com/ricmoo/aes-js

Google "block cipher vs stream cipher" to see which is best for you. I think block cipher, so you pad out the message to a certain length. You also need to come up with a way of storing the keys. For a portfolio piece you could perhaps simplify, use the same key everywhere and write "//imagine a secure key storage and exchange thing goes here". Then you can expand into public/private key pairs and Diffie-Hellmann key exchange later.

TheIncredulousHulk
Sep 3, 2012

Thanks!

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

I'm writing tests for functions that deal with strings that are ints. Like:

JavaScript code:
const x = "4130"
I'm struggling for what to call that.

"A string that contains an int"?

"A stringified int"?

"A string of only digits"?

Why is my brain failing me here?

mystes
May 31, 2006

Thermopyle posted:

I'm writing tests for functions that deal with strings that are ints. Like:

JavaScript code:
const x = "4130"
I'm struggling for what to call that.

"A string that contains an int"?

"A stringified int"?

"A string of only digits"?

Why is my brain failing me here?
How about "numeric string"?

necrotic
Aug 2, 2005
I owe my brother big time for this!
The latter sounds the best.

edit: numeric string could also work but could imply decimals as well.

Joda
Apr 24, 2010

When I'm off, I just like to really let go and have fun, y'know?

Fun Shoe
Integer string

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
fractionless whole natural sequence encoded byte array

ynohtna
Feb 16, 2007

backwoods compatible
Illegal Hen
strinteger

Osmosisch
Sep 9, 2007

I shall make everyone look like me! Then when they trick each other, they will say "oh that Coyote, he is the smartest one, he can even trick the great Coyote."



Grimey Drawer
charray

Cheen
Apr 17, 2005

String with numeric characteristics

roomforthetuna
Mar 22, 2005

I don't need to know anything about virii! My CUSTOM PROGRAM keeps me protected! It's not like they'll try to come in through the Internet or something!
asciint

NotWearingPants
Jan 3, 2006

by Nyc_Tattoo
Nap Ghost
pre-parseInt integer.

prisoner of waffles
May 8, 2007

Ah! well a-day! what evil looks
Had I from old and young!
Instead of the cross, the fishmech
About my neck was hung.
"string matching the regex /^-?\d+$/"

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

So far, all equally-great ideas!

Jazerus
May 24, 2011


"a mistake"

MrMoo
Sep 14, 2000

Does anyone know how to properly implement a texture atlas in modern THREE.js that uses geometry based UVs instead of hacking offset/repeat in the texture and cloning it's UUID? The latter now results in multiple texture uploads to the GPU.

I'm after a Sprite and PlaneGeometry based Mesh detail for a texture atlas and anything to do with UVs is confusing the hell out of me. I can see THREE.js examples for Minecraft have a texture atlas for BoxGeometry but that doesn't easily translate.

I've managed various messed up results, didn't save the really odd ones with trippy random dots and odd angles.






demo

It's supposed to look like this:

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
I have looked at two (or three) new APIs in the last week. Service workers + caches seems like a really good and simple API and Indexed DB looks like complicated garbage.

It's really easy to cache a few resources and then just serve them from the cache forever while everything else uses normal http requests.

Indexed DB looks like a ton of yak shaving before you get to the part where you can dump data in there.

I was looking at Indexed DB because Safari on ios doesn't share localstorage with PWAs and that's where our app's auth keys are stored, but then I read that it doesn't share Indexed DB either. So I guess our iphone users get to log in again with the app.

necrotic
Aug 2, 2005
I owe my brother big time for this!
IndexedDB is the foundation for building a database on. There are quite a few extensive database libraries built on it providing SQL or document type interfaces you should use instead

This is even mentioned on the MDN page https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API

MrMoo
Sep 14, 2000

The docs make it look worse that it needs to be. For simple key-value storage if you don't have localstorage, it is manageable. Wrapping in Promises is probably the way to go, something like this:
JavaScript code:
await open_db();
let store = get_object_store(DB_STORE, "readonly");
function wrap(request) {
        return new Promise((resolve, reject) => {
                request.onsuccess = resolve;
                request.onerror = e => {
                        console.error(e);
                        reject(e);
                };
        });
}
return wrap(store.get("settings"))

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
I have an actual javascript question: does cache.addAll guarantee that those files will always stay cached?

Currently my service worker just caches all the js, css, images and fonts that the app uses using addAll (8 files, a little over 1 megabyte total) and the fetch listener will just return the cached version or fetch the resource if not found in cache. The cache is never updated.

Should I be checking if the requested resources match the files listed in addAll and re-cache them if they have been purged?

necrotic
Aug 2, 2005
I owe my brother big time for this!

https://developer.mozilla.org/en-US/docs/Web/API/Cache posted:

You are also responsible for periodically purging cache entries. Each browser has a hard limit on the amount of cache storage that a given origin can use. Cache quota usage estimates are available via the StorageEstimate API. The browser does its best to manage disk space, but it may delete the Cache storage for an origin. The browser will generally delete all of the data for an origin or none of the data for an origin. Make sure to version caches by name and use the caches only from the version of the script that they can safely operate on. See Deleting old caches for more information

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
I've read that before but I guess what I wanted to hear was that everything in the cache is treated equally and can disappear from under you. I guess that makes the default boilerplate javascript that keeps static resources cached a bit more complex.

Or can the browser just reinstall the service worker after a cache purge?

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
My react knowledge is old an rusty, so I look up a 2019 react article and see this:

JavaScript code:
const [state, setState] = useState(initialState);
:eyepop: now that's what I'm here for. No writing setters for me.

Roadie
Jun 30, 2013

Wheany posted:

My react knowledge is old an rusty, so I look up a 2019 react article and see this:

JavaScript code:
const [state, setState] = useState(initialState);
:eyepop: now that's what I'm here for. No writing setters for me.

Keep in mind that hooks have some weird gotchas, because basically there's some dumb magic going on there where it keeps track of hooks by just what calls to useWhatever get made in order, so you'll break stuff if you put one inside an if or do other flow control things with them. Also, you have to be careful about stale callbacks.

If you can keep a handle on all that, though, they're very useful for abstracting away "initial state" vs "current state" handling, especially once you add in a library for declarative-style data loading with hooks.

Adbot
ADBOT LOVES YOU

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
Everything I've ever read about hooks has been:

Some guy: I finally get hooks, they're really simple! Here's a fun thing you can do with hooks
React maintainer: Actually, this will break in edge case A, B, C. Use this obscure feature instead
Some guy: oh... hm...

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply