nitrictech / dart-sdk

Dart integration for Nitric.
https://nitric.io
Apache License 2.0
5 stars 4 forks source link

Issue deploying with shared database resources #39

Open chimon2000 opened 1 month ago

chimon2000 commented 1 month ago

Bug Report

Issue

Upon deploying, I see the following runtime error when attempting to hit an endpoint that pulls data from the SQL Database:

gRPC Error (code: 9, codeName: FAILED_PRECONDITION, message: NITRIC_DATABASE_BASE_URL environment variable not set, details: [], rawResponse: null, trailers: {})

This occurs because I define a shared global resource for the database accessed inside a method handler.

final db = Nitric.sql('db');
final api = Nitric.api('api');

void main(List<String> arguments) {
  api.get("/hello", (ctx) async {
    /// Causes database resource to be created
    await db.connectionString();
    return ctx;
  });
}

The hypothesis posed by @tjholm is that globally defined variables are lazily evaluated. We could verify this by reassigning the database resource inside of main:

final db = Nitric.sql('db');
final api = Nitric.api('api');

void main(List<String> arguments) {
  /// Causes database resource to be created
  final myDb = db;

  api.get("/hello", (ctx) async {
    await myDb.connectionString();
    return ctx;
  });
}

Other resources such as the previously defined api don't have this problem because they are initialized or referenced directly inside of the main function for each service.

Steps

Steps to reproduce the behavior:

Attempt to deploy the following project: https://github.com/chimon2000/db-deploy-issue

Expected

The database is created and seeded before the API is referenced.

Environment and setup information

Other info

Conversation thread: https://discord.com/channels/955259353043173427/999455789146181683/1287084311916445727

tjholm commented 1 week ago

@chimon2000 I think the pattern you've used in: https://github.com/chimon2000/notes_nitric, is a good demonstration of database sharing can be achieved for Dart.

Applying recommendations for Option 2 in: https://github.com/nitrictech/cli/issues/812 and updating the Dart guides for resource sharing are probably the best way to address this.