React native - Expo SQLite - Unable to resolve module ../assets/terezeen.db - react-native

I installed the expo SQLite package with the expo filesystem and assets package.
I am trying to load a pre-configured database but I keep getting these errors:
Android Bundling failed 341ms
Unable to resolve module ../assets/terezeen.db from D:\Skola\Vysoka\bakala\frontend\App.js:
None of these files exist:
* terezeen.db
* ..\assets\terezeen.db\index(.native|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx|.android.js|.native.js|.js|.android.jsx|.native.jsx|.jsx|.android.json|.native.json|.json)
23 | }
24 | await FileSystem.downloadAsync(
> 25 | Asset.fromModule(require("../assets/terezeen.db")).uri,
| ^
26 | FileSystem.documentDirectory + "SQLite/terezeen.db"
27 | );
28 | return SQLite.openDatabase("terezeen.db", "1.0");
App.js
import * as SQLite from 'expo-sqlite';
import * as FileSystem from 'expo-file-system';
import { Asset } from 'expo-asset';
async function openDb() {
if (!(await FileSystem.getInfoAsync(FileSystem.documentDirectory + "SQLite")).exists) {
await FileSystem.makeDirectoryAsync(FileSystem.documentDirectory + "SQLite");
}
await FileSystem.downloadAsync(
Asset.fromModule(require("../assets/terezeen.db")).uri,
FileSystem.documentDirectory + "SQLite/terezeen.db"
);
return SQLite.openDatabase("terezeen.db", "1.0");
}
export default function App() {
const db = openDb();
metro.config.js
const { getDefaultConfig } = require("metro-config");
module.exports = (async () => {
const {
resolver: { sourceExts, assetExts },
} = await getDefaultConfig();
return {
transformer: {
babelTransformerPath: require.resolve(
"react-native-svg-transformer"
),
},
resolver: {
assetExts: [
assetExts.filter((ext) => ext !== "svg"),
assetExts.push('db')
],
sourceExts: [...sourceExts, "svg"],
},
};
})();
react-native.config.js
module.exports = {
project: {
ios: {},
android: {}
},
assets:['./assets/fonts/'],
dependencies: {
"react-native-sqlite-storage": {
platforms: {
android: {
sourceDir:
"../node_modules/react-native-sqlite-storage/platforms/android-native",
packageImportPath: "import io.liteglue.SQLitePluginPackage;",
packageInstance: "new SQLitePluginPackage()"
}
}
}
}
}
File tree:
|assets
|--fonts
| |--font.otf <-- here is the method
|--terezeen.db
|
|src
|--assets <- just for case of the problem
|--fonts
|--font.otf
|--terezeen.db
|
|App.js <- file that calls the sqlite
After the installation of those expo packages I am also disallowed to use custom font because now it won't find it.

I have edited the metro.config.js like this:
const { getDefaultConfig } = require('expo/metro-config');
const defaultConfig = getDefaultConfig(__dirname);
defaultConfig.resolver.assetExts.push('db');
module.exports = defaultConfig;
Also, I thought that the directory of the database should be linked with android, so instead of linking it in the root directory I was linking it with the android directory.
Now the code looks like this:
async function openDb() {
if (!(await FileSystem.getInfoAsync(FileSystem.documentDirectory + "SQLite")).exists) {
await FileSystem.makeDirectoryAsync(FileSystem.documentDirectory + "SQLite");
}
await FileSystem.downloadAsync(
Asset.fromModule(require("./src/assets/terezeen.db")).uri,
FileSystem.documentDirectory + "SQLite/terezeen.db"
);
return SQLite.openDatabase("terezeen.db", "1.0");
}
export default function App() {
const db = openDb();

Related

React native couldn't resolve local module after noHoist has been added to project

I have this monorepo js setup with yarn workspaces and lerna
/package.json
/packages
/common (js shared code)
/package.json
/mobile (react native - metro)
/package.json
/web (CRA)
/package.json
Mobile and web packages are importing common package inside package.json as follow
"dependencies": {
"common": "*",
}
I had to add noHoist option in root package.json so that mobile native dependencies don't get hoisted so build scripts still run fine
"workspaces": {
"packages": [
"packages/*"
],
"nohoist": [
"**/react-native",
"**/react-native/**"
]
}
Web did work fine before and after adding noHoist option
React native metro bundling start failing after adding noHoist .. it shows
"Error: Unable to resolve module .. could not be found within the project or in these directories:
node_modules
../../node_modules"
However common package does actually exists under root node_modules ?
Looks like some kind of a linking issue ! (did try to link it manually/ same issue) .. note that I didn't add common package under noHoist
here how my metro config looks like
const path= require('path');
const watchFolders = [
path.resolve(`${__dirname}`), // Relative path to package node_modules
path.resolve(`${__dirname}/../../node_modules`), // Relative path to root node_modules ];
module.exports = {
transformer: {
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: true,
},
}),},
maxWorkers: 2,
watchFolders, };
ANY IDEA ? 🧐
Turns out the issue was in bundling, fixed by editing metro.config.js to include blocklist and extraNodeModules
const path = require('path');
const exclusionList = require('metro-config/src/defaults/exclusionList');
const getWorkspaces = require('get-yarn-workspaces');
function generateAssetsPath(depth, subpath) {
return `/assets`.concat(
Array.from({ length: depth })
// eslint-disable-next-line no-unused-vars
.map((_, i) => `/${subpath}`)
.join(''),
);
}
function getMetroAndroidAssetsResolutionFix(params = {}) {
const { depth = 3 } = params;
let publicPath = generateAssetsPath(depth, 'dir');
const applyMiddleware = (middleware) => (req, res, next) => {
// eslint-disable-next-line no-plusplus
for (let currentDepth = depth; currentDepth >= 0; currentDepth--) {
const pathToReplace = generateAssetsPath(currentDepth, 'dir');
const replacementPath = generateAssetsPath(depth - currentDepth, '..');
if (currentDepth === depth) {
publicPath = pathToReplace;
}
if (req.url.startsWith(pathToReplace)) {
req.url = req.url.replace(pathToReplace, replacementPath);
break;
}
}
return middleware(req, res, next);
};
return {
publicPath,
applyMiddleware,
};
}
function getNohoistedPackages() {
// eslint-disable-next-line global-require
const monorepoRootPackageJson = require('../../package.json');
const nohoistedPackages = monorepoRootPackageJson.workspaces.nohoist
.filter((packageNameGlob) => !packageNameGlob.endsWith('**'))
.map((packageNameGlob) => packageNameGlob.substring(3));
return nohoistedPackages;
}
function getMetroNohoistSettings({
dir,
workspaceName,
reactNativeAlias,
} = {}) {
const nohoistedPackages = getNohoistedPackages();
const blockList = [];
const extraNodeModules = {};
nohoistedPackages.forEach((packageName) => {
extraNodeModules[packageName] =
reactNativeAlias && packageName === 'react-native'
? path.resolve(dir, `./node_modules/${reactNativeAlias}`)
: path.resolve(dir, `./node_modules/${packageName}`);
const regexSafePackageName = packageName.replace('/', '\\/');
blockList.push(
new RegExp(
`^((?!${workspaceName}).)*\\/node_modules\\/${regexSafePackageName}\\/.*$`,
),
);
});
return { extraNodeModules, blockList };
}
const workspaces = getWorkspaces(__dirname);
const androidAssetsResolutionFix = getMetroAndroidAssetsResolutionFix({
depth: 3,
});
const nohoistSettings = getMetroNohoistSettings({
dir: __dirname,
workspaceName: 'mobile',
});
module.exports = {
transformer: {
// Apply the Android assets resolution fix to the public path...
// publicPath: androidAssetsResolutionFix.publicPath,
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: true,
},
}),
},
// server: {
// // ...and to the server middleware.
// enhanceMiddleware: (middleware) =>
// androidAssetsResolutionFix.applyMiddleware(middleware),
// },
// Add additional Yarn workspace package roots to the module map.
// This allows importing importing from all the project's packages.
watchFolders: [
path.resolve(__dirname, '../../node_modules'),
...workspaces.filter((workspaceDir) => !(workspaceDir === __dirname)),
],
maxWorkers: 2,
resolver: {
// Ensure we resolve nohoisted packages from this directory.
blockList: exclusionList(nohoistSettings.blockList),
extraNodeModules: nohoistSettings.extraNodeModules,
},
};
You can check this universal CRA/RN mono-repo that uses such metro configs

vue3 testing library - How to use globalProperties in tests

I am new to Vue and followed the recommendation to use vue testing library. The only issue is I can't seem to find a way to inject my code into globalProperties in render function.
Does anyone know of an example where I can inject or mock it out?
main.js
app.config.globalProperties.$globals = globalMethods
...
const app = createApp(App)
app.config.globalProperties.$globals = globalMethods
app.config.globalProperties.$globalVars = globalVars
app.component("font-awesome-icon", fontawesome)
app.use(applicationStore);
app.use (Hotjar, hotjarConfig)
app.use(i18n)
app.use(router)
app.mount('#app')
From my vue component in create I am able to call
Component.vue
let formatedObj = this.$globals.maskValues(this.inputValue, this.inputType, this);
...
,
created() {
let formatedObj = this.$globals.maskValues(this.inputValue, this.inputType, this);
this.myInputValue = formatedObj.formatedString;
this.formatedCharacterCount = formatedObj.formatedCharacterCount;
this.prevValue = this.myInputValue;
},
...
tesst.spec.js
import { render } from '#testing-library/vue'
import FormatedNumericInput from '#/components/Component.vue'
import {globalMethods} from'#/config/global-methods'
const label = 'Price'
const initSettings = {
props: {
inputId: 'testInputId1',
labelTxt: label
}
};
beforeEach(() => {
});
test('a simple string that defines your test', () => {
const { getByLabelText } = render(FormatedNumericInput, initSettings)
const input = getByLabelText(label)
// testing logic
expect(input != null).toBe(true)
expect(FormatedNumericInput != null).toBe(true)
})
** ERROR **
TypeError: Cannot read property 'maskValues' of undefined
85 | },
86 | created() {
> 87 | let formatedObj = this.$globals.maskValues(this.inputValue, this.inputType, this);
| ^
88 | this.myInputValue = formatedObj.formatedString;
89 | this.formatedCharacterCount = formatedObj.formatedCharacterCount;
90 | this.prevValue = this.myInputValue;
at Proxy.created (src/components/FormatedNumericInput.vue:87:37)
The second argument of render() is passed to #vue/test-utils mount(), so you could include the global.mocks mounting option to mock $globals.maskValues:
const { getByLabelText } = render(FormatedNumericInput, {
...initSettings,
global: {
mocks: {
$globals: {
maskValues: (inputValue, inputType) => {
const formatedString = globalFormatValue(inputValue) // declared elsewhere
return {
formatedString,
formatedCharacterCount: formatedString.length,
}
}
}
}
}
})
This is my solution in actual Vue3/Vite/Vitest environment, I set some mocks globally, so I don't need to in every test suite.
// vitest.config.ts
import { mergeConfig } from 'vite';
import { defineConfig } from 'vitest/config';
import viteConfig from './vite.config';
export default defineConfig(
mergeConfig(viteConfig, { // extending app vite config
test: {
setupFiles: ['tests/unit.setup.ts'],
environment: 'jsdom',
}
})
);
// tests/unit.setup.ts
import { config } from "#vue/test-utils"
config.global.mocks = {
$t: tKey => tKey; // just return translation key
};
so for you it will be something like
config.global.mocks = {
$globals: {
maskValues: (inputValue, inputType) => {
// ...implementation
return {
formatedString,
formatedCharacterCount,
}
}
}
}

How to parse serverless.yml file in script

I need to read the serverless.yml config for use in some test mocks.
The following worked until a recent change:
const serverless = new Serverless()
await serverless.init()
const service = await serverless.variables.populateService()
How does one read the file now? There is an astounding lack of documentation in regards to using serverless progamically.
Well I ended up taking some code from the AppSync emulator package. I am not sure it covers it does a full parsing but it does the job for me.
import Serverless from 'serverless'
import path from 'path'
import fs from 'fs'
class ConfigServerless extends Serverless {
async getConfig(servicePath) {
this.processedInput = {
commands: [],
options: { stage: 'dev' }
}
this.config.servicePath = servicePath
this.pluginManager.setCliOptions(this.processedInput.options)
this.pluginManager.setCliCommands(this.processedInput.commands)
await this.service.load(this.processedInput)
this.pluginManager.validateCommand(this.processedInput.commands)
return this.variables
.populateService(this.pluginManager.cliOptions)
.then(() => {
this.service.mergeArrays()
this.service.setFunctionNames(this.processedInput.options)
this.service.validate()
})
}
}
const normalizeResources = config => {
if (!config.resources) {
return config.resources
}
if (!config.resources.Resources) {
return {}
}
if (!Array.isArray(config.resources.Resources)) {
return config.resources
}
const newResources = config.resources.Resources.reduce(
(sum, { Resources, Outputs = {} }) => ({
...sum,
...Resources,
Outputs: {
...(sum.Outputs || {}),
...Outputs
}
}),
{}
)
return {
Resources: newResources
}
}
export async function loadServerlessConfig(cwd = process.cwd()) {
const stat = fs.statSync(cwd)
if (!stat.isDirectory()) {
cwd = path.dirname(cwd)
}
const serverless = new ConfigServerless()
await serverless.getConfig(cwd)
const { service: config } = serverless
const { custom = {} } = config
const output = {
...config,
custom: {
...custom
},
resources: normalizeResources(config)
}
return output
}

How do you enable 'require(*/*.vrx)' using rn-cli.config?

The Metro bundler for react-native cli is unable to resolve a .vrx file (used for a viroreact AR scene).
I've tried to create an rn-cli.config.js file in the project root that should have sorted it but it isn't. What am I missing?
I've tried to create an rn-cli.config.js file in the project root that should have sorted it but it isn't. What am I missing?
The path specified is definitely correct in the requiring .js
rn-cli.config.js
const { getDefaultConfig } = require("metro-config");
module.exports = (async () => {
const {
resolver: { assetExts }
} = await getDefaultConfig();
return {
resolver: {
assetExts: [...assetExts, "obj", "mtl", "JPG", "vrx", "fbx", "hdr"]
}
};
})();
Metro bundler reporting this error
error: bundling failed: Error: Unable to resolve module `./js/res/coffee_mug/object_coffee_mug.vrx` from `C:\Users\Dave\Documents\schoolOfCode\Final Project\final-project-app-brumgo-front-end\components\ARtest\index.js`: The module `./js/res/coffee_mug/object_coffee_mug.vrx` could not be found from `C:\Users\Dave\Documents\schoolOfCode\Final Project\final-project-app-brumgo-front-end\components\ARtest\index.js`. Indeed, none of these files exist:
Please update the metro.config.js at the root of your project as follows.
const {getDefaultConfig} = require('metro-config');
module.exports = (async () => {
const {
resolver: {assetExts},
} = await getDefaultConfig();
return {
resolver: {
assetExts: [
...assetExts,
'obj',
'mtl',
'JPG',
'vrx',
'hdr',
'gltf',
'glb',
'bin',
'arobject',
'gif',
],
},
};
})();

Background Geolocation For Ionic2

i'm trying to use background geolocation , i found this link :
[a link] https://www.joshmorony.com/adding-background-geolocation-t…/ .
"Geoposition is not knwon " type script error .
ionic version :2.2.1 , node version :6.10.0 , cordova version:6.5.0 .any suggestion for ionic2 geoloca
location-tracker :
import { Injectable, NgZone } from '#angular/core';
import { Geolocation,Geoposition, BackgroundGeolocation } from 'ionic-native';
import 'rxjs/add/operator/filter';
#Injectable()
export class LocationTracker {
public watch: any;
public lat: number = 0;
public lng: number = 0;
constructor(public zone: NgZone) {
}
startTracking() {
// Background Tracking
let config = {
desiredAccuracy: 0,
stationaryRadius: 20,
distanceFilter: 10,
debug: true,
interval: 2000
};
BackgroundGeolocation.configure((location) => {
console.log('BackgroundGeolocation: ' + location.latitude + ',' + location.longitude);
// Run update inside of Angular's zone
this.zone.run(() => {
this.lat = location.latitude;
this.lng = location.longitude;
});
}, (err) => {
console.log(err);
}, config);
// Turn ON the background-geolocation system.
BackgroundGeolocation.start();
// Foreground Tracking
let options = {
frequency: 3000,
enableHighAccuracy: true
};
this.watch = Geolocation.watchPosition(options).filter((p: any) => p.code === undefined).subscribe((position: Geoposition ) => {
console.log(position);
// Run update inside of Angular's zone
this.zone.run(() => {
this.lat = position.coords.latitude;
this.lng = position.coords.longitude;
});
});
}
stopTracking() {
console.log('stopTracking');
BackgroundGeolocation.finish();
this.watch.unsubscribe();
}
}
tion
Assuming that you have already run the following commands;
ionic plugin add cordova-plugin-geolocation
npm install --save #ionic-native/geolocation
ionic plugin add cordova-plugin-mauron85-background-geolocation
npm install --save #ionic-native/background-geolocation
try importing the plugins as follows:
import { BackgroundGeolocation } from '#ionic-native/background-geolocation';
import { Geolocation, Geoposition } from '#ionic-native/geolocation';