https://cypress.io logo
In my project i have Postgres DB, so i just added ...
# best-practices
p
In my project i have Postgres DB, so i just added node-postgres library to the project and whenever i need something from the database I have commands that directly interact with it. Its very simple and good approach imo. I dont have any adding or deleting information from the db, but instead i take information that would require a lot of code and API calls, or sometimes i get info from DB that i dont even have available via API
h
Thanks for the input, I appreciate it! I'll check the library since we also use Postgres in our project.
p
First import the library Add this to index.js in plugins folder, rather use enviromental variables
Copy code
js
  on("task", {
    DATABASE({ config, dbName, port, sql, values }) {
      config.database = dbName;
      config.port = port;
      const pool = new pg.Pool(config);
      try {
        return pool.query(sql, values);
      } catch (e) {}
    },
  });
Then simply call the task in a custom command or directly in tests (second one I find very anti-pattern, personally prefer code and tests to be completely separate)
Copy code
js
    cy.task("DATABASE", {
      config: postgres, // add to env
      dbName: "clients", //write on each separate
      port: 9999,  //add to env
      sql: `select player from clients 
      where player_name = '${username}'`, //directly copy paste sql query
    }).then((result) => {
     results = result.rows[0].username; // get the results by using results.rows[0]
    });
I hope this helps