I'm using the Module Auth with ORM driver and native sessions.
The database config 'default' and 'customer_1' exists in application/config/database.php.
Before login i change the default database config with:
Kohana::$config->load('database')->default = Kohana::$config->load('database')->get('customer_1');
This does work before Module Auth login!
After setting the default database config:
if (Auth::instance()->login($_POST['username'], $_POST['password']) === TRUE) { Request::current()->redirect(); }
This results in the following error:
Table 'default_database.users' doesn't exist [ SHOW FULL COLUMNS FROM `users` ]
For some reason it use the initial default database config.
My Question: How do i set the default database for Module Auth ?
Let's follow this through a bit.
You're actually using ORM/Auth and not just Auth. ORM in ORM/Auth is configured to use the default database if one isn't specified. It lets you override this option by overloading $_db_group in the ORM.php file.
Let's use Kohana's cascading filesystem to overwrite that. Make a new file: classes/auth.php . Insert this code:
<?php
class ORM extends Kohana_ORM {
$_db_group = Kohana::$config->load('database')->get('customer_1');
}
All set.
If you want Auth module to use different database then other models, you should use $_db_group as suggested by Gaurav Patel. However you should override only Auth ORM models (user, role and user_token), not ORM class:
APPATH/classes/model/user.php:
class Model_User extends Model_Auth_User
{
protected $_db_group = 'customer_1';
}
APPATH/classes/model/role.php:
class Model_Role extends Model_Auth_Role
{
protected $_db_group = 'customer_1';
}
APPATH/classes/model/user/token.php:
class Model_User_Token extends Model_Auth_User_Token
{
protected $_db_group = 'customer_1';
}
Related
Update: I have fixed it by only supplying the pattern of the path of the collection, and creating a function that can parse the provided IDs and now the functions themselves create the collections when they are called upon and it also works with Typescript:)
Updated in the repository:
https://github.com/Darkbound/nestjs-firebase/tree/main/src/firebase
In the user service:
https://github.com/Darkbound/nestjs-firebase/blob/main/src/user/user.service.ts
In the purchase transactions service: https://github.com/Darkbound/nestjs-firebase/blob/main/src/user/modules/purchase-transaction/purchase-transaction.service.ts
In the purchase transactions controller: https://github.com/Darkbound/nestjs-firebase/blob/main/src/user/modules/purchase-transaction/purchase-transaction.controller.ts#L14
Now the functionality works out of the box, the service class simply needs to extend the FirebaseCollectionService and give it the pattern of the path to the collection and thats it!
https://github.com/Darkbound/nestjs-firebase I have uploaded it into a repository, you only need to add .env with the keys for firebase admin.
And the specific example: https://github.com/Darkbound/nestjs-firebase/blob/main/src/user/modules/purchase-transaction/purchase-transaction.service.ts
I have created a class that gives me the functionality to perform CRUD operations on firebase, so that I can just directly inherit from it for any of my CRUD resources, as the logic is again usually mostly the same. Just like Nestjs generator gives me all of the routes for it.
#Injectable()
export class UserService extends NestjsFirebase<User> {
constructor(#InjectFirebaseAdmin() firebase: FirebaseAdmin) {
super(firebase, "users");
// console.log(userId);
}
}
This works great, I can reuse that for any level 1 collection I have in firebase, however if I want to get into a nested collection on firebase, well thats a problem, because the path there needs to be dynamic and super(firebase, "this is no longer just users").
Say if I want to access the transactions of a user, so users/SomeUserIdXYZ/transactions, then the path is entirely dependent on the userId and is changing, therefor, I need to recreate the instance of the service (I simply need a new instance of the class), with a new path:
super(firebase, ["users", userId, "transactions"]
However with my still limited knowledge about Nestjs I know that everything in it basically is a Singleton and there is probably no way to do this? To get a new instance of the service, for every request that I have?
The solution that I can think of is, to handle that within my route functions, so if its a findTransactions:
#Get("users/:userId/transactions")
async findTransactions(#Param("userId") userId: string) {
return this.userService.findAll(`users/${userId}/transactions`);
}
And I am pretty sure that this will work, if I add a path argument to each of the functions, but this seems like coupling the Controller with what my Path in firebase should look like, instead I need to be able to give it just the params so that it can create its own path.
This is NestjsFirebase:
#Injectable()
class NestjsFirebase<T> {
constructor(#InjectFirebaseAdmin() private readonly firebase: FirebaseAdmin, private readonly collectionPath: string) {}
async findAll(userId: string): Promise<T> {
const db = new FirebaseCollectionService<T>(this.firebase, this.collectionPath);
return await db.findAll(userId);
}
}
export class FirebaseCollectionService<T> {
protected db: CollectionReference<T>;
constructor(firebase: FirebaseAdmin, collectionPath: string) {
super(firebase.db);
this.db = this.createCollectionPath(collectionPath);
}
public async findAll(id: string) {
... some logic to find all transactions ...
}
}
How can i store a default record using the migration file?
In symfony/doctrine there are a method like postUp() which is missing in shopware.
So how can i do this? The shopware doc provides a tutorial Creating data with a given ID, but i cannot initialize the needed repository.
So how can i access the entityRepository inside the migration class? Or is there another way to create a default record?
The recommended way is to just create the table in the migration file and then upsert the default records in the activate and update methods of the Plugin class. See answer by #dneustadt
Please read the comments to this answer for further information.
You can't use an EntityRepository inside a migration file. You can only use raw SQL queries by using the $connection variable which is passed to the update method.
Example:
<?php declare(strict_types=1);
namespace Swag\BasicExample\Migration;
use Doctrine\DBAL\Connection;
use Shopware\Core\Framework\Migration\MigrationStep;
use Shopware\Core\Framework\Uuid\Uuid;
class Migration1611740369ExampleDescription extends MigrationStep
{
public function getCreationTimestamp(): int
{
return 1611740369;
}
public function update(Connection $connection): void
{
// create table
$createTableSql = <<<SQL
CREATE TABLE IF NOT EXISTS `swag_basic_example_general_settings` (
`id` INT NOT NULL,
`example_setting` VARCHAR(255) NOT NULL,
`created_at` DATETIME(3) NOT NULL,
`updated_at` DATETIME(3),
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
SQL;
$connection->executeStatement($createTableSql);
// insert default setting
$insertDefaultSettingSql = <<<SQL
INSERT INTO `swag_basic_example_general_settings`
(`id`, `example_setting`, `created_at`)
VALUES (:id, :example_setting, NOW())
SQL;
$connection->executeStatement(
$insertDefaultSettingSql,
[
'id' => Uuid::randomBytes(),
'example_setting' => 'example_value',
]
);
}
public function updateDestructive(Connection $connection): void
{
}
}
Note: When using Connection instead of an entity repository you need to use Uuid::randomBytes() instead of Uuid::randomHex(). If you want to use an existing ID instead of a generated one you can use Uuid::fromHexToBytes('0fa91ce3e96a4bc2be4bd9ce752c3425')
Inside the Plugin extension you can access the DI container and get any public services including the repositories:
class MyPlugin extends Plugin
{
public function activate(ActivateContext $context)
{
$productRepository = $this->container->get('product.repository');
}
}
Im working on a team that has a bunch of services so we have a npm package that contains code shared between the services.
We have a Health check module that sets the path to globalPrefix/health. Im attempting to make this value configurable in a maintainable way.
#Injectable()
#Controller()
export class HealthController {
private readonly healthCheckOptions: HealthConfigurationOptions;
private readonly url: string;
constructor(
#Inject('CONFIGURATION_OPTIONS') private options: HealthConfigurationOptions,
private readonly healthService: HealthService,
) {
this.healthCheckOptions = options || {}
this.url = options.url
}
#Get(this.url)
async healthHandler(): Promise<HealthDto | TmoHttpException> {
return this.healthService.getStatus();
}
}
My idea was to create a Dynamic Module that can take a path as an option. In the example above There is a Dynamic Health Module that accepts an options object. But it seems like during compilation the route handler is set before the class is constructed meaning that i cannot use this.url like #Get(this.url) because there is no this yet.
At this point Im a bit stumped and haven't found anything online doing what I need.
Reflect.defineMetadata(PATH_METADATA, 'my_custom_path', MyController);
while registering your custom dynamic module will change the path of your controller. however there are still issues with this approach.
see here: https://github.com/nestjs/nest/issues/1438#issuecomment-1324011241
I am using Breeze with much success in my SPA, but seem to be stuck when trying to return parent->child data in a single query by using expand().
When doing a single table query, the $type in the JSON return is correct:
$type: MySPA.Models.Challenge, MySPA
However if I use expand() in my query I get the relational data, but the $type is this:
System.Collections.Generic.Dictionary 2[[System.String, mscorlib],[System.Object, mscorlib]]
Because of the $type is not the proper table + namespace, the client side code can't tell that this is an entity and exposes it as JSON and not a Breeze object (with observables, entityAspect, etc.).
At first I was using my own ContextProvider so that I could override the Before/After saving methods. When I had these problems, I reverted back to the stock EFContextProvider<>.
I am using EF5 in a database first mode.
Here's my controller code:
[BreezeController]
public class DataController : ApiController
{
// readonly ModelProvider _contextProvider = new ModelProvider();
readonly EFContextProvider<TestEntities> _contextProvider = new EFContextProvider<TestEntities>();
[HttpGet]
public string Metadata()
{
return _contextProvider.Metadata();
}
[Queryable(AllowedQueryOptions = AllowedQueryOptions.All)]
[HttpGet]
public IQueryable<Challenge> Challenges()
{
return _contextProvider.Context.Challenges;
}
[HttpPost]
public SaveResult SaveChanges(JObject saveBundle)
{
return _contextProvider.SaveChanges(saveBundle);
}
public IQueryable<ChallengeNote> ChallengeNotes()
{
return _contextProvider.Context.ChallengeNotes;
}
}
Here's my BreezeWebApiConfig.cs
public static void RegisterBreezePreStart()
{
GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
GlobalConfiguration.Configuration.Routes.MapHttpRoute(
name: "BreezeApi",
routeTemplate: "breeze/{controller}/{action}"
);
}
Is there a configuration setting that I am missing?
Did you try "expanding" on server side? Is it needed to do expand on client side? I tried to do expand before but failed for me as well, did some research and decided I'd rather place it on server:
[HttpGet]
public IQueryable<Challenge> ChallengesWithNotes()
{
return _contextProvider.Context.Challenges.Include("ChallengeNotes");
}
This should be parsed as expected. On client side you would query for "ChallengeNotes" instead of "Challenges" and you wouldn't need to write expand part.
I strongly suspect that the problem is due to your use of the [Queryable] attribute.
You must use the [BreezeQueryable] attribute instead!
See the documentation on limiting queries.
We are aware that Web API's QueryableAttribute has been deprecated in favor of EnableQueryAttribute in Web API v.1.5. Please stick with BreezeQueryable until we've had a chance to write a corresponding derived attribute for EnableQuery. Check with the documentation for the status of this development.
I'm trying to re-use some of the model configurations on several entities that implements a interface.
Check this code:
public static void ConfigureAsAuditable<T>(this EntityTypeConfiguration<T> thisRef)
where T : class, IAuditable
{
thisRef.Property(x => x.CreatedOn)
.HasColumnName("utctimestamp")
.IsRequired();
thisRef.Property(x => x.LastUpdate)
.HasColumnName("utclastchanged")
.IsRequired();
} // ConfigureAsAuditable
as you can see I'm trying to call the extension method "ConfigureAsAuditable" on my onmodelcreating method like this:
EntityTypeConfiguration<Account> conf = null;
conf = modelBuilder.Entity<Account>();
conf.ToTable("dbo.taccount");
conf.ConfigureAsAuditable();
When debugging i get this exception:
The property 'CreatedOn' is not a declared property on type
'Account'. Verify that the property has not been explicitly excluded
from the model by using the Ignore method or NotMappedAttribute data
annotation. Make sure that it is a valid primitive property.
Thanks in advance :)
PD:
I'm using EF 5-rc, VS 2011 and .NET Framework 4.5
I think a better approach would be to implement your own derived version of EntityTypeConfiguration. For example:
public class MyAuditableConfigurationEntityType<T> : EntityTypeConfiguration<T>
where T : class, IAuditable{
public bool IsAuditable{get;set;}
}
Then, when building your model, use that new type:
var accountConfiguration = new MyAuditableConfigurationEntityType<Account>();
accountConfiguration.IsAuditable = true; // or whatever you need to set
accountConfiguration.(HasKey/Ignore/ToTable/Whatever)
modelBuilder.Configurations.Add(accountConfiguration);