0

I'm currently building a NodeJS express API to run with a ReactJS front end. Coming from mongodb where everything is a document I'm a little bit lost about how to gather data from SQL. Let me explain.

To build a ReactJS application working with an API Rest I need proper Objects structure in front end.

Taking the example of a basic application where a user can place bets on a match, I would have

TABLE users (
  _id SERIAL PRIMARY KEY,

  username varchar(255) UNIQUE,
  password varchar(255)
);

TABLE matches (
    _id SERIAL PRIMARY KEY,

    EQA varchar(255), // These should be ids to teams but
    EQB varchar(255), // we try to keep it simple

    EQA_score INTEGER,
    EQB_score INTEGER,
);

TABLE bets (
    _id SERIAL PRIMARY KEY,
    user_id INTEGER REFERENCES users(_id),
    match_id INTEGER REFERENCES matches(_id),

    EQA_bet INTEGER,
    EQB_bet INTEGER,
);

Then to display the history of the pronostics in ReactJS it would be very simple with datas structured this way:

{
    username: 'Random name',
    bets: [
        {
            EQA_bet: 1,
            EQB_bet: 0,
            match: {
                EQA: 'Paris',
                EQB: 'London',
                EQA_score: 1,
                EQB_score: 0,

            }
        },
        {
            ...
        }
    ]
}

To build this object I don't know what would be the best:

  • One query for user, bets and matches and build my object in JS
  • One query with joins then some long code to build my object
  • Some other tools / strategies I don't know yet

Thanks for understanding my issue. This is all about not having a flat object to interpret in front end

1
  • You are looking for a SQL ORM. I have worked with Objection.js and I love it. The feature you need is called eager loading Commented Apr 4, 2019 at 21:01

1 Answer 1

1

@Yooomi, you can use sequelize NPM Package to create your object models and can define relationships between different models. You can do all C.R.U.D. operations through this. The response you get through this package will be in JSON format. You can change it as per your need.

You can go through different blogs and find the usage of the sequelize. I search on google and found this article which seems a good start.

Let me know if that is useful.

Sign up to request clarification or add additional context in comments.

2 Comments

I'm taking a look at this and this seems to fill the job, but I'm quite sad I won't write my SQL queries on my own
Yeah, That is the whole purpose of changing the SQL table to an object model to avoid SQL statements and let the framework handle all CRUD operations. If you seems I gave you the answer then, please like my original answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.