How to use planetscale with fastify properly?

37 views Asked by At

I am quite new to the NodeJS and the I/O system that it brings, so I am still learning the ropes. I come from a background in Laravel and Wordpress.

I have been trying to set up a fastify API server that connects to Planetscale DB, I am using the Fastify/mysql package.

import Fastify from "fastify";
import fastifyMysql from "@fastify/mysql";

app.register(fastifyMysql, {
uri: process.env.DATABASE_URL,
type: 'pool',
promise: true,
multipleStatements: false } );

try {
await app.listen({
port: 2000
})
} catch (err) {
app.log.error(err);
process.exit(1);
}

this is how I am registering it

I couldn't find any docs on it's pooling - but read that it takes care of it mostly - that said I have tried different mysql2 options in the parameters.

My issue is in regards to my connections.

export async function someFunction( fastify, id ) {
if (!validator.isNumeric(id)) {
throw new Error('Invalid slug');
}

    const connection = await fastify.mysql.getConnection();

    const course_query = 
        `A SQL QUERY`;
    const lessons_query = 
        `A SQL QUERY`;

// const [a] = await connection.query(a_query, [id]);
// const [b] = await connection.query(b_query, [id]);

    const [[a], [b], c] = await Promise.all([
        connection.query(a_query, [id]),
        connection.query(b_query, [id]),
        connection.query(c_query, [id])
    ]);

    connection.release();

    return {
        a: a,
        b: b
    }

}

I then use this function in the actual route - which is in a plugin thus I pass the fastify app to it - which in turn is able to get the mysql connection in the function.

fastify.get("/details/:id", async (request, reply) => {
 try {
     const data = await someFunction(fastify, request.params.id);
     reply.code(200).send(data);
    }
    catch (error) {
        reply.code(400).send({ message: error.message });
 }

My issue is in regards to the timing.

So in wordpress and laravel I can make 100's of sql queries (Not that I would want to... but usually on a good server - it comes back very quickly) - Now, yes I am assuming there would be some latency due to distance with planetscale.

But what I am finding is that the time taken is directly attributed to how many queries I make.

For example, if I just have query a - it will take 200ms a + c 400ms

just c = 200ms

a + c + b =600ms

so I can only assume that they are all each firing after one another. I am unsure if this is expected behaviours within the nature of NodeJS - and if so how might I go about fixing this (Not with different structured queries)

All the best.

I have tried using mysql2 with pools, wrapping in promise. All

using try

using promises

I just cannot seem to figure this out or if this is intended

0

There are 0 answers