How to config applicatiuon.yml when using Micronaut + GORM with multiple data sources - grails-orm

Environmant: Java 11 + Micronaut 2.1 + GORM.
I have two databases to connect. PostgreSQL and MSSQL. I have tried some ways looked up in Internet but all failed. Below is my detail configuration, code, and output log. Please instruct me how to correctly config application.yml. Thanks
Reference sites:
Grails Multi-datasource
GORM for Hibernate
My application.yml is as below:
micronaut:
application:
name: demo
---
hibernate:
hbm2ddl:
auto: none
cache:
queries: false
use_second_level_cache: false
use_query_cache: false
---
dataSource:
dbCreate: none
url: jdbc:postgresql://localhost/test_db1
dialect: org.hibernate.dialect.PostgreSQLDialect
pooled: true
jmxExport: true
driverClassName: org.postgresql.Driver
username: 'user1'
password: 'user1'
dataSources:
emp:
pooled: true
jmxExport: true
dialect: org.hibernate.dialect.SQLServer2012Dialect
driverClassName: com.microsoft.sqlserver.jdbc.SQLServerDriver
dbCreate: none
url: jdbc:sqlserver://localhost:1433;databaseName=test_db2
username: 'user2'
password: 'user2'
My entity classes:
import grails.gorm.annotation.Entity
import org.springframework.context.i18n.LocaleContextHolder
#Entity
class Country {
String enDisplayName;
static mapping = {
version false
}
static constraints = {
enDisplayName nullable: false
}
}
#Entity
class Employee {
String employeeId
String employeeName
static mapping = {
dataSource 'emp'
version false
id name:'employeeId', generator:'assigned'
}
}
My Main code:
package com.example
import com.example.domain.Country
import com.example.domain.Employee
import io.micronaut.configuration.picocli.PicocliRunner
import io.micronaut.context.ApplicationContext
import picocli.CommandLine
import picocli.CommandLine.Command
import picocli.CommandLine.Option
import picocli.CommandLine.Parameters
#Command(name = 'demo', description = '...',
mixinStandardHelpOptions = true)
class DemoCommand implements Runnable {
#Option(names = ['-v', '--verbose'], description = '...')
boolean verbose
static void main(String[] args) throws Exception {
PicocliRunner.run(DemoCommand.class, args)
}
void run() {
// business logic here
if (verbose) {
println "Hi!"
}
Country.withNewSession {
List<Country> list = Country.list()
println("Country count:${list.size()}")
}
Employee.withNewSession {
Employee employee = Employee.findByEmployeeNo('BU4191')
println("employee name:${employee.employeeName}")
}
}
}
log:
16:25:26.624 [main] INFO i.m.context.env.DefaultEnvironment - Established active environments: [cli]
16:25:26.928 [main] INFO i.m.c.h.g.HibernateDatastoreFactory - Starting GORM for Hibernate
16:25:27.558 [main] INFO org.hibernate.Version - HHH000412: Hibernate ORM core version 5.4.21.Final
16:25:27.682 [main] INFO o.h.validator.internal.util.Version - HV000001: Hibernate Validator 6.1.5.Final
16:25:27.819 [main] INFO o.h.annotations.common.Version - HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
16:25:28.646 [main] INFO org.hibernate.dialect.Dialect - HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
16:25:29.609 [main] INFO org.hibernate.dialect.Dialect - HHH000400: Using dialect: org.hibernate.dialect.SQLServer2012Dialect
Country count:4
16:25:30.253 [main] WARN org.hibernate.orm.deprecation - HHH90000022: Hibernate's legacy org.hibernate.Criteria API is deprecated; use the JPA javax.persistence.criteria.CriteriaQuery instead
16:25:30.283 [main] WARN o.h.e.jdbc.spi.SqlExceptionHelper - SQL Error: 0, SQLState: 42703
16:25:30.283 [main] ERROR o.h.e.jdbc.spi.SqlExceptionHelper - ERROR: column this_.employee_id does not exist
Position: 8
org.springframework.jdbc.BadSqlGrammarException: Hibernate operation: could not extract ResultSet; bad SQL grammar [n/a]; nested exception is org.postgresql.util.PSQLException: ERROR: column this_.employee_id does not exist
Position: 8
at org.springframework.jdbc.support.SQLStateSQLExceptionTranslator.doTranslate(SQLStateSQLExceptionTranslator.java:101)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:72)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81)
at org.grails.orm.hibernate.GrailsHibernateTemplate.convertJdbcAccessException(GrailsHibernateTemplate.java:725)
at org.grails.orm.hibernate.GrailsHibernateTemplate.convertHibernateAccessException(GrailsHibernateTemplate.java:712)
at org.grails.orm.hibernate.GrailsHibernateTemplate.doExecute(GrailsHibernateTemplate.java:301)
at org.grails.orm.hibernate.GrailsHibernateTemplate.execute(GrailsHibernateTemplate.java:241)
at org.grails.orm.hibernate.GrailsHibernateTemplate.executeWithNewSession(GrailsHibernateTemplate.java:153)
at org.grails.orm.hibernate.AbstractHibernateDatastore.withNewSession(AbstractHibernateDatastore.java:360)
at org.grails.orm.hibernate.AbstractHibernateGormStaticApi.withNewSession(AbstractHibernateGormStaticApi.groovy:78)
at org.grails.datastore.gorm.GormEntity$Trait$Helper.withNewSession(GormEntity.groovy:1027)
at org.grails.datastore.gorm.GormEntity$Trait$Helper$withNewSession.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:148)
at com.example.domain.Employee.withNewSession(Employee.groovy)
at com.example.domain.Employee$withNewSession.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:139)
at com.example.DemoCommand.run(DemoCommand.groovy:34)
at picocli.CommandLine.executeUserObject(CommandLine.java:1919)
at picocli.CommandLine.access$1100(CommandLine.java:145)
at picocli.CommandLine$RunLast.executeUserObjectOfLastSubcommandWithSameParent(CommandLine.java:2332)
at picocli.CommandLine$RunLast.handle(CommandLine.java:2326)
at picocli.CommandLine$RunLast.handle(CommandLine.java:2291)
at picocli.CommandLine$AbstractParseResultHandler.execute(CommandLine.java:2159)
at picocli.CommandLine.execute(CommandLine.java:2058)
at io.micronaut.configuration.picocli.PicocliRunner.run(PicocliRunner.java:137)
at io.micronaut.configuration.picocli.PicocliRunner.run(PicocliRunner.java:114)
at io.micronaut.configuration.picocli.PicocliRunner$run.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:148)
at com.example.DemoCommand.main(DemoCommand.groovy:21)
Caused by: org.postgresql.util.PSQLException: ERROR: column this_.employee_id does not exist
Position: 8

Eventually, I have tried the successful result as below:
micronaut:
application:
name: demo
dataSource:
url: jdbc:h2:mem:devDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
driverClassName: org.h2.Driver
username: sa
password: ''
pooled: true
jmxExport: true
hibernate:
hbm2ddl:
auto: update
cache:
queries: false
use_second_level_cache: false
use_query_cache: false
dataSources:
seconddb:
url: jdbc:h2:mem:devDb2;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
driverClassName: org.h2.Driver
username: sa
password: ''
readOnly: true
pooled: true
jmxExport: true
hibernate:
hbm2ddl:
auto: update
cache:
queries: false
use_second_level_cache: false
use_query_cache: false

Related

Not established connection in TypeORM

I've got a problem with running migrations in TypeORM. Right now when I launch yarn typeorm migration:run, he throw me this error:
CannotExecuteNotConnectedError: Cannot execute operation on "default" connection because connection is not yet established.
Can someone tell me what it mean?
Here is also my configuration:
ormconfig.ts
let connectionSource;
if (!process.env.PG_HOST) {
connectionSource = new DataSource({
type: "sqlite",
database: "sqlite_db",
entities: [join(__dirname, "./lib/db/entities/*.entity.{js,ts}")],
});
} else {
connectionSource = new DataSource({
type: "postgres",
host: process.env.PG_HOST,
port: +process.env.PG_PORT,
username: process.env.PG_USER,
database: process.env.PG_DB_NAME,
password: process.env.PG_PASS,
entities: [join(__dirname, "./lib/db/entities/*.entity.{js,ts}")],
migrations: [join(__dirname, "./lib/db/migrations/*.{js,ts}")],
migrationsTransactionMode: "each",
migrationsRun: true,
synchronize: true,
logging: false
});
}
export default connectionSource as DataSource;
script:
"typeorm": "ts-node ./node_modules/typeorm/cli.js -d ormconfig.ts",
I read that it can be a problem with initialize connection before running migrations, but how do this with using NestJS?
Thanks for any help!

Serverless: TypeError: Cannot read property 'stage' of undefined

frameworkVersion: '2'
plugins:
- serverless-step-functions
- serverless-python-requirements
- serverless-parameters
- serverless-pseudo-parameters
provider:
name: aws
region: us-east-2
stage: ${opt:stage, 'dev'}
runtime: python3.7
versionFunctions: false
iam:
role: arn:aws:iam::#{AWS::AccountId}:role/AWSLambdaVPCAccessExecutionRole
apiGateway:
shouldStartNameWithService: true
lambdaHashingVersion: 20201221
package:
exclude:
- node_modules/**
- venv/**
# Lambda functions
functions:
generateAlert:
handler: handler.generateAlert
generateData:
handler: handler.generateDataHandler
timeout: 600
approveDenied:
handler: handler.approveDenied
timeout: 600
stepFunctions:
stateMachines:
"claims-etl-and-insight-generation-${self:provider.stage}":
loggingConfig:
level: ALL
includeExecutionData: true
destinations:
- Fn::GetAtt: ["ETLStepFunctionLogGroup", Arn]
name: "claims-etl-and-insight-generation-${self:provider.stage}"
definition:
Comment: "${self:provider.stage} ETL Workflow"
StartAt: RawQualityJob
States:
# Raw Data Quality Check Job Start
RawQualityJob:
Type: Task
Resource: arn:aws:states:::glue:startJobRun.sync
Parameters:
JobName: "data_quality_v2_${self:provider.stage}"
Arguments:
"--workflow-name": "${self:provider.stage}-Workflow"
"--dataset_id.$": "$.datasetId"
"--client_id.$": "$.clientId"
Next: DataQualityChoice
Retry:
- ErrorEquals: [States.ALL]
MaxAttempts: 2
IntervalSeconds: 10
BackoffRate: 5
Catch:
- ErrorEquals: [States.ALL]
Next: GenerateErrorAlertDataQuality
# End Raw Data Quality Check Job
DataQualityChoice:
Type: Task
Resource:
Fn::GetAtt: [approveDenied, Arn]
Next: Is Approved ?
Is Approved ?:
Type: Choice
Choices:
- Variable: "$.quality_status"
StringEquals: "Denied"
Next: FailState
Default: HeaderLineJob
FailState:
Type: Fail
Cause: "Denied status"
# Header Line Job Start
HeaderLineJob:
Type: Parallel
Branches:
- StartAt: HeaderLineIngestion
States:
HeaderLineIngestion:
Type: Task
Resource: arn:aws:states:::glue:startJobRun.sync
Parameters:
JobName: headers_lines_etl_rs_v2
Arguments:
"--workflow-name.$": "$.Arguments.--workflow-name"
"--dataset_id.$": "$.Arguments.--dataset_id"
"--client_id.$": "$.Arguments.--client_id"
End: True
Retry:
- ErrorEquals: [States.ALL]
MaxAttempts: 2
IntervalSeconds: 10
BackoffRate: 5
Catch:
- ErrorEquals: [States.ALL]
Next: GenerateErrorAlertHeaderLine
End: True
# Header Line Job End
GenerateErrorAlertDataQuality:
Type: Task
Resource:
Fn::GetAtt: [generateAlert, Arn]
End: true
resources:
Resources:
# Cloudwatch Log
"ETLStepFunctionLogGroup":
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: "ETLStepFunctionLogGroup_${self:provider.stage}"
This is what my serverless.yml file looks like.
When I run the command:
sls deploy --stage staging
It show
Type Error ----------------------------------------------
TypeError: Cannot read property 'stage' of undefined
at Variables.getValueFromOptions (/snapshot/serverless/lib/classes/Variables.js:648:37)
at Variables.getValueFromSource (/snapshot/serverless/lib/classes/Variables.js:579:17)
at /snapshot/serverless/lib/classes/Variables.js:539:12
Your Environment Information ---------------------------
Operating System: linux
Node Version: 14.4.0
Framework Version: 2.30.3 (standalone)
Plugin Version: 4.5.1
SDK Version: 4.2.0
Components Version: 3.7.4
How I can fix this? I tried with different version of serverless.
There is error in yamlParser file, which is provided by serverless-step-functions.
Above is my serverless config file.
It looks like a $ sign is missing from your provider -> stage?
provider:
name: aws
region: us-east-2
stage: ${opt:stage, 'dev'} # $ sign is missing?
runtime: python3.7
versionFunctions: false
iam:
role: arn:aws:iam::#{AWS::AccountId}:role/AWSLambdaVPCAccessExecutionRole
apiGateway:
shouldStartNameWithService: true
lambdaHashingVersion: 20201221

How to set provider.apiGateway.shouldStartNameWithService in a serverless.ts file?

I am kicking off a new project with a new Serverless TypeScript monorepo! Used the aws-nodejs-typescript template, which gave a serverless.ts config file. After some weeks, I am now getting the nice warning below from Serverless on command line:
Serverless: Deprecation warning: Starting with next major version, API Gateway naming will be changed from “{stage}-{service}” to “{service}-{stage}”.
Set “provider.apiGateway.shouldStartNameWithService” to “true” to adapt to the new behavior now.
More Info: https://www.serverless.com/framework/docs/deprecations/#AWS_API_GATEWAY_NAME_STARTING_WITH_SERVICE
Ok! Looks great, and I like the new naming. And since it’s a new project, better to apply the new naming now, before we release anything. However, it looks like the TypeScript definitions are rather strict, and do not seem to allow for the new variable yet:
Loading failed with: TSError: ⨯ Unable to compile TypeScript:
serverless.ts(44,7): error TS2322: Type ‘{ minimumCompressionSize: number; shouldStartNameWithService: true; }’ is not assignable to type ‘ApiGateway’.
Object literal may only specify known properties, and ‘shouldStartNameWithService’ does not exist in type ‘ApiGateway’.
awsProvider.d.ts(51, 9): The expected type comes from property ‘apiGateway’ which is declared here on type ‘Provider’
Is there a way to set the new property without reverting everything to YAML, which would be somewhat painful at this point?
Update 1
Many thanks to #NexGen for the pointer! Here is a minimal serverless.ts (emphasis on the TS!) showing the solution.
import type { Serverless, ApiGateway } from 'serverless/aws';
const serverlessConfiguration: Serverless = {
service: {
name: 'foo',
},
frameworkVersion: '2',
custom: {
webpack: {
webpackConfig: './webpack.config.js',
packager: 'yarn',
includeModules: true,
},
alerts: {
stages: ['stage', 'prod'],
definitions: {
functionErrors: { treatMissingData: 'notBreaching' },
},
alarms: ['functionErrors'],
},
},
package: {
individually: true,
},
plugins: [
'serverless-webpack',
'serverless-jest-plugin',
'serverless-plugin-aws-alerts',
],
provider: {
name: 'aws',
runtime: 'nodejs12.x',
region: 'us-west-2',
stage: "${opt:stage, 'dev'}",
apiGateway: {
minimumCompressionSize: 1024,
shouldStartNameWithService: true,
} as ApiGateway,
environment: {
AWS_NODEJS_CONNECTION_REUSE_ENABLED: '1',
},
},
};
module.exports = serverlessConfiguration;
It is really simple to apply this change, all what you need to do is to add this to your serverless.yml file.
provider:
apiGateway:
shouldStartNameWithService: true
provider: {
name: 'aws',
runtime: 'nodejs12.x',
apiGateway: {
shouldStartNameWithService: true
} as ApiGateway,
stage: 'dev'
}

Symfony 3.4 JMS Serializer DoctrineObjectConstructor::__construct() expect ManagerRegistry, instance of Doctrine\Bundle\DoctrineBundle\Registry given

Please help me , I am stuck here. I have recently upgraded Symfony version from 2.8 to Symfony 3.4 LTS version. All works fine except the Rest API end point where I extend the Sonata\UserBundle\Controller\Api\UserController on my custom controller. When i run the API i get the following error
Type error: Argument 1 passed to JMS\Serializer\Construction\DoctrineObjectConstructor::__construct() must be an instance of Doctrine\Persistence\ManagerRegistry, instance of Doctrine\Bundle\DoctrineBundle\Registry given, called in /var/www/html/var/cache/dev/Container9bzqz8e/appDevDebugProjectContainer.php on line 3303
This started happening after the upgrade.
My Controller
use FOS\RestBundle\View\View;
use Sonata\UserBundle\Controller\Api\UserController as SonataUserController;
use League\Fractal\Manager;
use League\Fractal\Resource\Item;
class CustomerUserController extends SonataUserController {
protected $formFactory;
/**
* #var CustomerUserService
*/
private $customerUserService;
/**
* #var Manager
*/
private $fractal;
/**
* CustomerUserController constructor.
* #param UserManagerInterface $userManager
* #param FormFactory $formFactory
* #param CustomerUserService $customerUserService
* #param LoggerInterface $logger
* #param GroupManagerInterface $groupManager
*/
public function __construct(
UserManagerInterface $userManager,
FormFactory $formFactory,
CustomerUserService $customerUserService,
LoggerInterface $logger,
GroupManagerInterface $groupManager
) {
parent::__construct($userManager, $groupManager, $formFactory);
$this->formFactory = $formFactory;
$this->customerUserService = $customerUserService;
$this->fractal = new Manager();
$this->logger = $logger;
$this->fractal->setSerializer(new CleanCollectionArraySerializer());
}
/**
* Retrieves a specific CustomerUser
*
* #param integer $id
* #return array
*/
public function getUserAction($id)
{
/** #var User $user */
$user = parent::getUserAction($id);
$this->ensureUserIsCustomerUser($user);
$this->fractal->parseIncludes('customer');
$userObject = new Item($user, new UserTransformer());
return $this->fractal->createData($userObject)->toArray();
}}
Composer Info
I have added only relevant bundles
doctrine/annotations 1.10.3
doctrine/cache 1.10.2
doctrine/collections 1.6.6
doctrine/common v2.8.1
doctrine/data-fixtures 1.3.3
doctrine/dbal v2.6.3
doctrine/doctrine-bundle 1.10.3
doctrine/doctrine-cache-bundle 1.4.0
doctrine/doctrine-fixtures-bundle v2.4.1
doctrine/doctrine-migrations-bundle v1.3.2
doctrine/inflector 1.4.3
doctrine/instantiator 1.0.5
doctrine/lexer 1.2.1
doctrine/migrations v1.8.1
doctrine/orm v2.5.14
friendsofsymfony/rest-bundle 2.8.1
friendsofsymfony/user-bundle v2.1.2
jms-serializer/serializer 1.3.0
jms/metadata 1.7.0
jms/parser-lib 1.0.0
jms/serializer 1.14.1
jms/serializer-bundle 2.4.4
sonata-project/user-bundle 4.5.1
Config.yaml
jms_serializer:
metadata:
directories:
AppUserBundle:
namespace_prefix: "App\\UserBundle"
path: "#AppUserBundle/Resources/config/serializer"
SonataUserBundle:
namespace_prefix: "Sonata\\UserBundle"
path: "#AppUserBundle/Resources/config/serializer"
FOSUserBundle:
namespace_prefix: "FOS\\UserBundle"
path: "#AppUserBundle/Resources/config/serializer"
fos_rest:
param_fetcher_listener: true
body_listener: true
format_listener: true
view:
view_response_listener: 'force'
formats:
json: true
force_redirects:
html: true
json: true
routing_loader:
default_format: json
body_converter:
enabled: true
validate: true
disable_csrf_role: ROLE_API
exception:
enabled: true
messages:
'App\UserBundle\Controller\Api\Exception': true
Serlializer Entity.User.yaml file
Sonata\UserBundle\Model\User:
exclusion_policy: ALL
properties:
firstname:
expose: true
groups: [sonata_api_read, sonata_api_write]
lastname:
expose: true
groups: [sonata_api_read, sonata_api_write]
FOS\UserBundle\Model\User:
exclusion_policy: ALL
properties:
id:
expose: true
groups: [sonata_api_read, sonata_api_write]
username:
expose: true
skip_when_empty: true
groups: [sonata_api_read, sonata_api_write]
email:
expose: true
skip_when_empty: true
groups: [sonata_api_read, sonata_api_write]
enabled:
expose: true
groups: [sonata_api_read, sonata_api_write]
locked:
expose: true
groups: [sonata_api_read, sonata_api_write]
expired:
expose: true
groups: [sonata_api_read, sonata_api_write]
credentialsExpired:
expose: true
skip_when_empty: true
groups: [sonata_api_read, sonata_api_write]
Any help much appreciated.
I manage to resolve the issue by explicitly adding
"jms/serializer-bundle": "^1.0 | ^2.4"
in my composer.json file.
Hope this helps someone

SailsJs - problems with lifting (orm hook failed to load)

I am having problems with running my app under windows. Normally, I am developing on Macbook but temporarly I had to switch. The thing is, that the app was already working on windows without problems. Here is an error message:
error: A hook (orm) failed to load!
verbose: Lowering sails...
verbose: Sent kill signal to child process (8684)...
verbose: Shutting down HTTP server...
verbose: HTTP server shut down successfully.
error: TypeError: Cannot read property 'config' of undefined
at validateModelDef (C:\projects\elearning-builder\node_modules\sails\node_modules\sails-hook-orm\lib
\validate-model-def.js:109:84)
at C:\projects\elearning-builder\node_modules\sails\node_modules\sails-hook-orm\lib\initialize.js:218
:36
at arrayEach (C:\projects\elearning-builder\node_modules\sails\node_modules\lodash\index.js:1289:13)
at Function. (C:\projects\elearning-builder\node_modules\sails\node_modules\lodash\index.j
s:3345:13)
at Array.async.auto._normalizeModelDefs (C:\projects\elearning-builder\node_modules\sails\node_module
s\sails-hook-orm\lib\initialize.js:216:11)
at listener (C:\projects\elearning-builder\node_modules\sails\node_modules\sails-hook-orm\node_module
s\async\lib\async.js:605:42)
at C:\projects\elearning-builder\node_modules\sails\node_modules\sails-hook-orm\node_modules\async\li
b\async.js:544:17
at _arrayEach (C:\projects\elearning-builder\node_modules\sails\node_modules\sails-hook-orm\node_modu
les\async\lib\async.js:85:13)
at Immediate.taskComplete (C:\projects\elearning-builder\node_modules\sails\node_modules\sails-hook-o
rm\node_modules\async\lib\async.js:543:13)
at processImmediate [as _immediateCallback] (timers.js:383:17)
PS C:\projects\elearning-builder>
I tried to check it out, what exactly is happening in \node_modules\sails\node_modules\sails-hook-orm\lib\validate-model-def.js:109:84
so I added simple console.log temporarly:
console.log("error in line below", hook);
var normalizedDatastoreConfig = hook.datastores[normalizedModelDef.connection[0]].config;
And as a result I see:
error in line below Hook {
load: [Function: wrapper],
defaults:
{ globals: { adapters: true, models: true },
orm: { skipProductionWarnings: false, moduleDefinitions: [Object] },
models: { connection: 'localDiskDb' },
connections: { localDiskDb: [Object] } },
configure: [Function: wrapper],
loadModules: [Function: wrapper],
initialize: [Function: wrapper],
config: { envs: [] },
middleware: {},
routes: { before: {}, after: {} },
reload: [Function: wrapper],
teardown: [Function: wrapper],
identity: 'orm',
configKey: 'orm',
models:
{ /* models here, I removed this as it was too long /*},
adapters: {},
datastores: {} }
So, the normalizedModelDef.connection[0] has value development. But hook.datastores is empty? That is why there is no config property.
But the thing is, I do have connections in my config/connections.js
Like here:
development: {
module : 'sails-mysql',
host : 'localhost',
port : 3306,
user : 'ebuilder',
password : 'ebuilder',
database : 'ebuilder'
},
production: {
/* details hidden ;) */
},
testing: {
/* details hidden ;) */
}
Any suggestions/tips highly appreciated.
You have some connections defined, but do you have the default connection defined that might be specified in config/models.js? If for example you have:
module.exports.models = {
connection: 'mysql',
...
then 'mysql' needs to be defined in your connections.js
As I see in your config/connections.js
development: {
module : 'sails-mysql',
host : 'localhost',
port : 3306,
user : 'ebuilder',
password : 'ebuilder',
database : 'ebuilder'
},
You have given module : 'sails-mysql which is not correct. It should be adapter:'sails-mysql'
development: {
adapter : 'sails-mysql',
host : 'localhost',
port : 3306,
user : 'ebuilder',
password : 'ebuilder',
database : 'ebuilder'
},
check your controller or models contains any error code. like any symbol. i had face same problem while my controller contain any character before or after api started