"errors":[{"rule":"required","field":"username","message":"required validation failed"} - adonis.js

i am trying to validate my user resister form in adonis js by using
import {schema, rules} from '#ioc:Adonis/Core/Validator';
after register I am getting error of
{"errors":[{"rule":"required","field":"username","message":"required validation failed"},{"rule":"required","field":"username","message":"required validation failed"},{"rule":"required","field":"password","message":"required validation failed"},{"rule":"required","field":"phone","message":"required validation failed"}]}
validation code is
import { HttpContextContract } from '#ioc:Adonis/Core/HttpContext';
import {schema, rules} from '#ioc:Adonis/Core/Validator';
import user from 'App/Models/User';
export default class LoginController{
public async loginShow({view}:HttpContextContract){
return view.render('backend/login');
}
public async register({request,response,auth}:HttpContextContract){
const userSchema = schema.create({
username: schema.string({trim:true},[rules.required(), rules.unique({table:'users', column:'username', caseInsensitive: true})]),
email: schema.string({trim:true},[rules.email(), rules.required(), rules.unique({table:'users', column:'email', caseInsensitive: true})]),
password: schema.string({},[rules.minLength(6), rules.maxLength(20)]),
phone: schema.string({},[rules.unique({table:'users', column:'phone'})])
})
const data = await request.validate({schema: userSchema})
const User = await user.create(data)
await auth.login(User)
return response.redirect('/')
}
public async registerShow({view}:HttpContextContract){
return view.render('backend/register');
}
public async login({request,response,auth}:HttpContextContract){
const {uid, password} = request.only(['uid','password'])
try{
await auth.attempt(uid,password)
} catch (error){
console.log('form','your email or password is incorrect')
return response.redirect().back()
}
return response.redirect('/')
}
}
migration table is given below:
import BaseSchema from '#ioc:Adonis/Lucid/Schema'
export default class Users extends BaseSchema {
protected tableName = 'users'
public async up () {
this.schema.createTable(this.tableName, (table) => {
table.increments('id')
table.string('name',50).nullable()
table.string('username',50).unique().notNullable()
table.string('email',100).unique().notNullable()
table.string('phone',18).unique().nullable()
table.string('password',50).notNullable()
table.string('country',30).nullable()
table.string('city',40).nullable()
table.string('address_1',40).nullable()
table.string('address_2',40).nullable()
table.string('token',40).nullable()
table.dateTime('token_expiry')
table.boolean('is_active').defaultTo(false)
table.timestamps(true,true)
})
}
public async down () {
this.schema.dropTable(this.tableName)
}
}

Related

wso2 is custom adaptive function not able to set claim

I am using wso2 IS 5.10, for adding custom claim which needs to be added by fetching from db I am using custom adaptive function. But the below code is not working.
package org.wso2.custom.auth.functions;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.identity.application.authentication.framework.config.model.graph.js.JsAuthenticatedUser;
import org.wso2.carbon.identity.application.authentication.framework.config.model.graph.js.JsAuthenticationContext;
import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import org.wso2.custom.auth.functions.internal.CustomAuthFuncComponent;
import org.wso2.carbon.identity.application.authentication.framework.config.model.graph.js.*;
public class SetForceAuthFunctionImpl implements SetForceAuthFunction {
private static final Log LOGGER = LogFactory.getLog(SetForceAuthFunctionImpl.class);
#Override
public JsAuthenticatedUser setForceAuth(JsAuthenticationContext context, boolean forceAuth) {
AuthenticatedUser lastAuthenticatedUser = context.getContext().getLastAuthenticatedUser();
LOGGER.info("lastAuthenticatedUser****:::::::::::"+lastAuthenticatedUser);
String userName = lastAuthenticatedUser.getUserName();
LOGGER.info("userName2****:::::::::::"+userName);
String tenantDomain = MultitenantUtils.getTenantDomain(userName);
String fullyQualifiedUserName=("USERS"+"/"+userName+"#"+tenantDomain);
Map<org.wso2.carbon.identity.application.common.model.ClaimMapping, String> claims = new HashMap<org.wso2.carbon.identity.application.common.model.ClaimMapping, String>();
claims.put(org.wso2.carbon.identity.application.common.model.ClaimMapping.build("test123", "test123", null, true), org.apache.commons.lang3.StringUtils.join("*******************",",,,"));
AuthenticatedUser authenticatedUserObj = AuthenticatedUser.createLocalAuthenticatedUserFromSubjectIdentifier(MultitenantUtils.getTenantAwareUsername
(fullyQualifiedUserName));
authenticatedUserObj.setAuthenticatedSubjectIdentifier(MultitenantUtils.getTenantAwareUsername
(fullyQualifiedUserName));
authenticatedUserObj.setUserAttributes(claims);
authenticatedUserObj.setUserName(MultitenantUtils.getTenantAwareUsername
(fullyQualifiedUserName));
return new JsAuthenticatedUser(authenticatedUserObj);
}
}
package org.wso2.custom.auth.functions.internal;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;
import org.wso2.carbon.identity.application.authentication.framework.JsFunctionRegistry;
import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.custom.auth.functions.GenerateHashFunction;
import org.wso2.custom.auth.functions.GenerateHashFunctionImpl;
import org.wso2.custom.auth.functions.GetClaimsForUsernameFunction;
import org.wso2.custom.auth.functions.GetClaimsForUsernameFunctionImpl;
import org.wso2.custom.auth.functions.GetUsernameFromContextFunction;
import org.wso2.custom.auth.functions.GetUsernameFromContextFunctionImpl;
import org.wso2.custom.auth.functions.SetForceAuthFunction;
import org.wso2.custom.auth.functions.SetForceAuthFunctionImpl;
#Component(
name = "custom.auth.functions.component",
immediate = true
)
public class CustomAuthFuncComponent {
private static final Log LOG = LogFactory.getLog(CustomAuthFuncComponent.class);
private static JsFunctionRegistry jsFunctionRegistry;
#Activate
protected void activate(ComponentContext ctxt) {
SetForceAuthFunction setForceAuthFunctionImpl = new SetForceAuthFunctionImpl();
jsFunctionRegistry.register(JsFunctionRegistry.Subsystem.SEQUENCE_HANDLER, "setForceAuth",
setForceAuthFunctionImpl);
GetUsernameFromContextFunction getUsernameFromContextFunctionImpl = new GetUsernameFromContextFunctionImpl();
jsFunctionRegistry.register(JsFunctionRegistry.Subsystem.SEQUENCE_HANDLER, "getUsernameFromContext",
getUsernameFromContextFunctionImpl);
GetClaimsForUsernameFunction getClaimsForUsernameFunctionImpl = new GetClaimsForUsernameFunctionImpl();
jsFunctionRegistry.register(JsFunctionRegistry.Subsystem.SEQUENCE_HANDLER, "getClaimsForUsername",
getClaimsForUsernameFunctionImpl);
GenerateHashFunction generateHashFunctionImpl = new GenerateHashFunctionImpl();
jsFunctionRegistry.register(JsFunctionRegistry.Subsystem.SEQUENCE_HANDLER, "generateHash",
generateHashFunctionImpl);
}
#Deactivate
protected void deactivate(ComponentContext ctxt) {
if (jsFunctionRegistry != null) {
jsFunctionRegistry.deRegister(JsFunctionRegistry.Subsystem.SEQUENCE_HANDLER, "setForceAuth");
jsFunctionRegistry.deRegister(JsFunctionRegistry.Subsystem.SEQUENCE_HANDLER, "getUsernameFromContext");
jsFunctionRegistry.deRegister(JsFunctionRegistry.Subsystem.SEQUENCE_HANDLER, "getClaimsForUsername");
jsFunctionRegistry.deRegister(JsFunctionRegistry.Subsystem.SEQUENCE_HANDLER, "generateHash");
}
}
#Reference(
name = "user.realmservice.default",
service = RealmService.class,
cardinality = ReferenceCardinality.MANDATORY,
policy = ReferencePolicy.DYNAMIC,
unbind = "unsetRealmService"
)
protected void setRealmService(RealmService realmService) {
if (LOG.isDebugEnabled()) {
LOG.debug("RealmService is set in the custom conditional authentication user functions bundle");
}
CustomAuthFuncHolder.getInstance().setRealmService(realmService);
}
protected void unsetRealmService(RealmService realmService) {
if (LOG.isDebugEnabled()) {
LOG.debug("RealmService is unset in the custom conditional authentication user functions bundle");
}
CustomAuthFuncHolder.getInstance().setRealmService(null);
}
#Reference(
name = "registry.service",
service = RegistryService.class,
cardinality = ReferenceCardinality.MANDATORY,
policy = ReferencePolicy.DYNAMIC,
unbind = "unsetRegistryService"
)
protected void setRegistryService(RegistryService registryService) {
if (LOG.isDebugEnabled()) {
LOG.debug("RegistryService is set in the custom conditional authentication user functions bundle");
}
CustomAuthFuncHolder.getInstance().setRegistryService(registryService);
}
protected void unsetRegistryService(RegistryService registryService) {
if (LOG.isDebugEnabled()) {
LOG.debug("RegistryService is unset in the custom conditional authentication user functions bundle");
}
CustomAuthFuncHolder.getInstance().setRegistryService(null);
}
#Reference(
service = JsFunctionRegistry.class,
cardinality = ReferenceCardinality.MANDATORY,
policy = ReferencePolicy.DYNAMIC,
unbind = "unsetJsFunctionRegistry"
)
public void setJsFunctionRegistry(JsFunctionRegistry jsFunctionRegistry) {
this.jsFunctionRegistry = jsFunctionRegistry;
}
public void unsetJsFunctionRegistry(JsFunctionRegistry jsFunctionRegistry) {
this.jsFunctionRegistry = null;
}
}
But when I am using setForceAuth(context, true); in adaptive authentication function to add custom claims its not working but working in custom authenticator.
Adaptive authentication script:
function onLoginRequest(context) {
doLogin(context);
}
function doLogin(context) {
executeStep(1,{
onSuccess: function (context) {
},
onFail: function(context){
executeStep(4,{
onSuccess: function (context) {
var subject = context.currentKnownSubject;
setForceAuth(context, true);
},
onFail: function(context){
}
});
}
});
}
The issue is that
setForceAuth(context, true);
executes the below code block
return new JsAuthenticatedUser(authenticatedUserObj);
There is no point in your code (authencation script or the java function) where the newly created JsAuthenticatedUser is set to the context.
What you need to do is to change the script like this
onSuccess: function (context) { context.currentKnownSubject = setForceAuth(context, true);}
or
the java function as below
`#Override
public JsAuthenticatedUser setForceAuth(JsAuthenticationContext context, boolean forceAuth) {
AuthenticatedUser lastAuthenticatedUser = context.getContext().getLastAuthenticatedUser();
LOGGER.info("lastAuthenticatedUser****:::::::::::"+lastAuthenticatedUser);
String userName = lastAuthenticatedUser.getUserName();
LOGGER.info("userName2****:::::::::::"+userName);
String tenantDomain = MultitenantUtils.getTenantDomain(userName);
String fullyQualifiedUserName=("USERS"+"/"+userName+"#"+tenantDomain);
Map<org.wso2.carbon.identity.application.common.model.ClaimMapping, String> claims = new HashMap<org.wso2.carbon.identity.application.common.model.ClaimMapping, String>();
claims.put(org.wso2.carbon.identity.application.common.model.ClaimMapping.build("test123", "test123", null, true), org.apache.commons.lang3.StringUtils.join("*******************",",,,"));
AuthenticatedUser authenticatedUserObj = AuthenticatedUser.createLocalAuthenticatedUserFromSubjectIdentifier(MultitenantUtils.getTenantAwareUsername
(fullyQualifiedUserName));
authenticatedUserObj.setAuthenticatedSubjectIdentifier(MultitenantUtils.getTenantAwareUsername
(fullyQualifiedUserName));
authenticatedUserObj.setUserAttributes(claims);
authenticatedUserObj.setUserName(MultitenantUtils.getTenantAwareUsername
(fullyQualifiedUserName));
context.getContext().setSubject(authenticatedUserObj);
}
Still it is not advisable to have a tenant aware user name on authentication scripts. Rather can you think of not using
setForceAuth()
function and use the provided user.localClaims[] instead?

Can't get registered user.id in AdonisJS when setting relationships in controller

My code:
users migration
public async up() {
this.schema.createTable(this.tableName, (table) => {
table.increments('id').primary()
table.string('password', 180).nullable()
table.timestamp('created_at', {useTz: true}).notNullable()
table.timestamp('updated_at', {useTz: true}).notNullable()
}
words migration
public async up() {
this.schema.createTable(this.tableName, (table) => {
table.increments('id')
table.timestamp('created_at', {useTz: true})
table.timestamp('updated_at', {useTz: true})
table.integer('user_id').unsigned().references('users.id').onDelete('CASCADE')
})
}
Models/User
#hasMany(() => Word)
public words: HasMany<typeof Word>
Models/Word
#column()
public userId: number
#belongsTo(() => User)
public author: BelongsTo<typeof User>
WordsController
public async store({request, auth}: HttpContextContract) {
const user = auth.user!.id
const data = await request.validate(WordValidator)
const word = await user?.related('words').create(data)
return word
}
When I type auth.user!.id as it is in upper example, it returns this:
"Cannot read properties of undefined (reading 'id')"
I'm registered, it even normally shows my id on other requests (but only get requests).
What can I do, to get registered user id, and set it as userId in word table or what am I doing wrong?
Thanks

Nestjs unit test: TypeError: this.userModel.findById(...).exec is not a function

using nestjs framework and with a repository class that uses mongoose to do the CRUD operations we have a simple users.repository.ts file like this:
#Injectable()
export class UserRepository {
constructor(#InjectModel(User.name) private userModel: Model<UserDocument>) {}
async create(createUserInput: CreateUserInput) {
const createdUser = new this.userModel(createUserInput);
return await createdUser.save();
}
}
async findById(_id: MongooseSchema.Types.ObjectId) {
return await this.userModel.findById(_id).exec();
}
and it works normally when the server is up.
consider this users.repository.spec file :
import { Test, TestingModule } from '#nestjs/testing';
import { getModelToken } from '#nestjs/mongoose';
import { Model } from 'mongoose';
// User is my class and UserDocument is my typescript type
// ie. export type UserDocument = User & Document; <-- Mongoose Type
import { User, UserDocument } from '../domain/user.model';
import { UserRepository } from './users.repository';
//import graphqlScalars from 'graphql-scalar-types';
describe('UsersRepository', () => {
let mockUserModel: Model<UserDocument>;
let mockRepository: UserRepository;
beforeAll(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
{
provide: getModelToken(User.name),
useValue: Model, // <-- Use the Model Class from Mongoose
},
UserRepository,
//graphqlScalars,
],
}).compile();
// Make sure to use the correct Document Type for the 'module.get' func
mockUserModel = module.get<Model<UserDocument>>(getModelToken(User.name));
mockRepository = module.get<UserRepository>(UserRepository);
});
it('should be defined', () => {
expect(mockRepository).toBeDefined();
});
it('should return a user doc', async () => {
// arrange
const user = new User();
const userId = user._id;
const spy = jest
.spyOn(mockUserModel, 'findById') // <- spy
.mockResolvedValue(user as UserDocument); // <- set resolved value
// act
await mockRepository.findById(userId);
// assert
expect(spy).toBeCalled();
});
});
so my question:
for the should return a user doc test i get TypeError: metatype is not a constructor when and i guess
.mockResolvedValue(user as UserDocument);
should be fixed.
Note:graphql is used the query to the API and i have no idea that if the scalars should be provieded or not, if i uncomment the scalar, the expect(mockRepository).toBeDefined(); test would not pass any more
so any idea to fix the test would be apreciated.
to handle a chained .exec we should define it via mockReturnThis():
static findById = jest.fn().mockReturnThis();
I needed the constructor to be called via new so i preferd to define a mock class in this way:
class UserModelMock {
constructor(private data) {}
new = jest.fn().mockResolvedValue(this.data);
save = jest.fn().mockResolvedValue(this.data);
static find = jest.fn().mockResolvedValue(mockUser());
static create = jest.fn().mockResolvedValue(mockUser());
static remove = jest.fn().mockResolvedValueOnce(true);
static exists = jest.fn().mockResolvedValue(false);
static findOne = jest.fn().mockResolvedValue(mockUser());
static findByIdAndUpdate = jest.fn().mockResolvedValue(mockUser());
static findByIdAndDelete = jest.fn().mockReturnThis();
static exec = jest.fn();
static deleteOne = jest.fn().mockResolvedValue(true);
static findById = jest.fn().mockReturnThis();
}

Angular 5 & Django REST - Issue uploading files

I developed an Angular application where the user can handle brands.
When creating/updating a brand, the user can also upload a logo. All data are sent to the DB via a REST API built using the Django REST Framework.
Using the Django REST Framework API website I'm able to upload files, but using Angular when I send data thu the API I get an error.
I also tried to encode the File object to base64 using FileReader, but I get the same error from Django.
Can you help me understanding the issue?
Models:
export class Brand {
id: number;
name: string;
description: string;
is_active: boolean = true;
is_customer_brand: boolean = false;
logo_img: Image;
}
export class Image {
id: number;
img: string; // URL path to the image (full size)
img_md: string; // medium size
img_sm: string; // small
img_xs: string; // extra-small/thumbnail
}
Service:
import { Injectable } from '#angular/core';
import { Http, Response } from '#angular/http';
import { Headers, RequestOptions } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { Brand } from './brand';
const endpoint = 'http://127.0.0.1:8000/api/brands/'
#Injectable()
export class BrandService {
private brands: Array<Brand>;
constructor(private http: Http) { }
list(): Observable<Array<Brand>> {
return this.http.get(endpoint)
.map(response => {
this.brands = response.json() as Brand[];
return response.json();
})
.catch(this.handleError);
}
create(brand: Brand): Observable<Brand> {
console.log(brand);
return this.http.post(endpoint+'create/', brand)
.map(response => response.json())
.catch(this.handleError);
}
get(id): Observable<Brand> {
return this.http.get(endpoint+id)
.map(response => response.json())
.catch(this.handleError);
}
private handleError(error:any, caught:any): any {
console.log(error, caught);
}
}
Error from the browser console:
"{"logo_img":{"img":["The submitted data was not a file. Check the
encoding type on the form."]}}"
Django Serializer:
class BrandSerializer(ModelSerializer):
is_active = BooleanField(required=False)
logo_img = ImageSerializer(required=False, allow_null=True)
class Meta:
model = Brand
fields = [
'id',
'name',
'description',
'is_active',
'is_customer_brand',
'logo_img',
]
def update(self, instance, validated_data):
image = validated_data.get('logo_img',None)
old_image = None
if image:
image = image.get('img',None)
brand_str = validated_data['name'].lower().replace(' ','-')
ext = validated_data['logo_img']['img'].name.split('.')[-1].lower()
filename = '{0}.{1}'.format(brand_str,ext)
user = None
request = self.context.get('request')
if request and hasattr(request, 'user'):
user = request.user
image_serializer_class = create_image_serializer(path='logos', filename=filename, created_by=user, img_config = {'max_w':3000.0,'max_h':3000.0,'max_file_size':1.5,'to_jpeg':False})
image_serializer = image_serializer_class(data=validated_data['logo_img'])
image_serializer.is_valid()
validated_data['logo_img'] = image_serializer.save()
old_image = instance.logo_img
super(BrandSerializer, self).update(instance,validated_data)
if old_image: # Removing old logo
old_image.img.delete()
old_image.img_md.delete()
old_image.img_sm.delete()
old_image.img_xs.delete()
old_image.delete()
return instance
def create(self, validated_data):
image = validated_data.get('logo_img',None)
print(image)
if image:
print(image)
image = image.get('img',None)
print(image)
brand_str = validated_data['name'].lower().replace(' ','-')
ext = validated_data['logo_img']['img'].name.split('.')[-1].lower()
filename = '{0}.{1}'.format(brand_str,ext)
user = None
request = self.context.get('request')
if request and hasattr(request, 'user'):
user = request.user
image_serializer_class = create_image_serializer(path='logos', filename=filename, created_by=user, img_config = {'max_w':3000.0,'max_h':3000.0,'max_file_size':1.5,'to_jpeg':False})
image_serializer = image_serializer_class(data=validated_data['logo_img'])
image_serializer.is_valid()
validated_data['logo_img'] = image_serializer.save()
return super(BrandSerializer, self).create(validated_data)
When posting a new brand to the server with files, I have three main choices:
Base64 encode the file, at the expense of increasing the data size by around 33%.
Send the file first in a multipart/form-data POST, and return an ID to the client. The client then sends the metadata with the ID, and the server re-associates the file and the metadata.
Send the metadata first, and return an ID to the client. The client then sends the file with the ID, and the server re-associates the file and the metadata.
The Base64 encoding will involve unacceptable payload.
So I choose to use multipart/form-data.
Here's how I implemented it in Angular's service:
create(brand: Brand): Observable<Brand> {
let headers = new Headers();
let formData = new FormData(); // Note: FormData values can only be string or File/Blob objects
Object.entries(brand).forEach(([key, value]) => {
if (key === 'logo_img') {
formData.append('logo_img_file', value.img);
} else {
formData.append(key, value);
});
return this.http.post(endpoint+'create/', formData)
.map(response => response.json())
.catch(this.handleError);
}
IMPORTANT NOTE: Since there's no way to have nested fields using FormData, I cannot append formData.append('logo_img', {'img' : FILE_OBJ }). I had change the API in order to receive the file in one field called logo_img_file.
Hope that my issue helped someone.

Ionic2 sqlitePlugin is not defined

How to evade this error: VM18193:27 Unable to open database ReferenceError: sqlitePlugin is not defined(…)
setTimeout(function() {
let db = new SQLite();
db.openDatabase({
name: "data.db",
location: "default"
}).then(() => {
db.executeSql("CREATE TABLE IF NOT EXISTS people (id INTEGER PRIMARY KEY AUTOINCREMENT, firstname TEXT, lastname TEXT)", {}).then((data) => {
console.log("TABLE CREATED: ", data);
}, (error) => {
console.error("Unable to execute sql", error);
})
}, (error) => {
console.error("Unable to open database", error);
});
}, 2000);
How can i execute some query?
if(SqlSettingsService.openDb){
this.db = SqlSettingsService.getDB();
this.db.executeSql("CREATE TABLE IF NOT EXISTS people (id INTEGER PRIMARY KEY AUTOINCREMENT, firstname TEXT, lastname TEXT", {}).then
instead i get error.
console:
SqlSettingsService() starts
VM21750:27 Unhandled Promise rejection: Cannot read property 'executeSql' of null ; Zone: <root> ; Task: Promise.then ; Value: TypeError: Cannot read property 'executeSql' of null(…) TypeError: Cannot read property 'executeSql' of null
The plugin sqlLite does not work in a browser, you can use Websql for the browser instead (with compatible browsers, including Chrome and Opera as far as I know).
Transactions written for Websql are compatible with transactions written for SQLite.
Here is a service I have done to manage the Connection to the DB and make it work regardless if the program runs in a browser or a on real device:
import { Injectable } from '#angular/core';
import { SQLite } from 'ionic-native';
import { Platform } from 'ionic-angular';
import { Storage } from '#ionic/storage';
#Injectable()
export class SqlSettingsService {
private db: any = null;
private isOpened: boolean = false;
constructor() {
console.log('SqlSettingsService() starts');
}
public getDB(){
return this.db;
}
public openDb = (platform:Platform,winSer:any):Promise<any> => {
console.log('SqlSettingsService() opend DB starts');
let p:Promise<any>;
if(!this.isOpened){
this.isOpened = true;
if(platform.is('core')){
this.db = winSer.window.openDatabase("ionic2BrowserDev","1.0","",5*1024*1024);
p = new Promise(function(resolve,reject){resolve('websql success')});
} else {
this.db = new SQLite();
p = this.db.openDatabase({
name: 'data.db',
location: 'default' // the location field is required
}).then(
()=>{console.log("SqlSettingsService open db successful")},
(err)=>{console.error(err)}
);
}
} else {
p = new Promise(function(resolve,reject){
resolve('db already opened');
});
}
return p;
}
public closeDb = () => {
this.isOpened = false;
return this.db.close();
}
}
winSer is another service to access the window Object that I use in my app.component.ts when I call openDB() on SqlSettingsService. It's just this:
import { Injectable } from '#angular/core';
#Injectable()
export class WindowService {
public window = window;
}
To execute query:
[SqlSettingsService-instance].openDb();
[SqlSettingsSevice-instance].getDB().transaction(
function(tx){
tx.executeSql([your sql],[bracket values you want to pass],success,error);
function success(tx,rs){
console.log("success exec sql: ")
console.info(rs);
}
function error(tx,error){
console.log('execSqlCustom error ' + error.message + " for tx " + tx);
}
});