Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

What's the proper way to access database/api? #42

Open
UROjQ6r80p opened this issue Jul 16, 2023 · 1 comment
Open

What's the proper way to access database/api? #42

UROjQ6r80p opened this issue Jul 16, 2023 · 1 comment

Comments

@UROjQ6r80p
Copy link

UROjQ6r80p commented Jul 16, 2023

Let's say I want to fetch products from the database.

that's the old way:

import express from "express";
import markoPlugin from "@marko/express";
import template from "./template.marko";

const app = express();
app.use(markoPlugin()); // Enables `res.marko(template, input)`

app.get("/", function (req, res) {
  const products = req.db.find(...)

  res.marko(template, {
    products
  });
});

app.listen(8080);

What's the proper way to do the same in marko/run?

I tried something like this in +handler.js

export const GET: MarkoRun.Handler = ({ request, platform }, next) => {
    platform.response.locals = {
        data: Math.random()
    }

    next()
};

and then in +page.marko
<h1>${$global.platform.response.locals.data}</h1>
but i'm not sure it's the best way.

@vwong
Copy link
Contributor

vwong commented Jul 16, 2023

I don't think this is the right forum to ask support questions like these; try https://discord.com/invite/marko next time.

But in short, I think the best way to do this is to add a +middleware.js early on, that appends your database connector to context aka $global, using something like context.dbClient = dbClient. This way, you only ever need to create +page.marko with <await($global.dbClient.find(...))> and don't have to litter your code with +handler.js everywhere.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants