Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

react-sqlite-hook

Package Overview
Dependencies
Maintainers
1
Versions
51
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-sqlite-hook - npm Package Compare versions

Comparing version 1.0.0-alpha.2 to 1.0.0-alpha.3

11

CHANGELOG.md

@@ -0,1 +1,12 @@

## 1.0.0-alpha.3 (2020-12-04) REFACTOR
### Added Features
- getPlatform
### Bug Fixes
- fix new SQLiteConnection with useMemo()
## 1.0.0-alpha.2 (2020-12-03) REFACTOR

@@ -2,0 +13,0 @@

4

dist/package.json
{
"name": "react-sqlite-hook",
"version": "1.0.0-alpha.1",
"version": "1.0.0-alpha.2",
"description": "React Hook for @Capacitor-community/sqlite plugin",

@@ -27,3 +27,3 @@ "repository": {

"build-old": "node scripts/build.js",
"docgen": "docgen --api ISQLiteHook --output-readme docs/APIHook.md",
"docgen": "docgen --api SQLiteHook --output-readme docs/APIHook.md",
"test": "jest"

@@ -30,0 +30,0 @@ },

import { AvailableResult } from './util/models';
import '@capacitor-community/sqlite';
import { SQLiteDBConnection } from '@capacitor-community/sqlite';
export { SQLiteDBConnection };
/**
* SQLite Hook Interface
*/
interface ISQLiteHook extends AvailableResult {
interface SQLiteHook extends AvailableResult {
/**

@@ -18,2 +19,10 @@ * Echo a value

/**
* Get platform
* @returns Promise<{platform: string}>
* @since 1.0.0 refactor
*/
getPlatform(): Promise<{
platform: string;
}>;
/**
* Add an Upgrade Statement to Update Database Version

@@ -79,3 +88,3 @@ * @param dbName database name

}
interface Result {
export interface Result {
result?: boolean;

@@ -87,3 +96,2 @@ message?: string;

*/
export declare function useSQLite(): ISQLiteHook;
export {};
export declare const useSQLite: () => SQLiteHook;

@@ -1,2 +0,2 @@

import { useCallback } from 'react';
import { useCallback, useMemo } from 'react';
import { Capacitor, Plugins } from '@capacitor/core';

@@ -6,29 +6,17 @@ import { notAvailable } from './util/models';

import '@capacitor-community/sqlite';
import { SQLiteConnection } from '@capacitor-community/sqlite';
import { SQLiteDBConnection, SQLiteConnection } from '@capacitor-community/sqlite';
export { SQLiteDBConnection };
/**
* useSQLite Hook
*/
export function useSQLite() {
export const useSQLite = () => {
const { CapacitorSQLite } = Plugins;
const platform = Capacitor.getPlatform();
const sqlitePlugin = CapacitorSQLite;
const mSQLite = new SQLiteConnection(sqlitePlugin);
let permissionsListener = null;
const mSQLite = useMemo(() => {
return new SQLiteConnection(sqlitePlugin);
}, [sqlitePlugin]);
const availableFeaturesN = {
useSQLite: isFeatureAvailable('CapacitorSQLite', 'useSQLite')
};
const androidPermissions = async () => {
try {
await sqlitePlugin.requestPermissions();
return { result: true };
}
catch (e) {
console.log("Error requesting permissions " + e);
return { result: false,
message: "Error requesting permissions " + e };
}
};
if (!availableFeaturesN.useSQLite) {
return Object.assign({ echo: featureNotAvailableError, createConnection: featureNotAvailableError, closeConnection: featureNotAvailableError, retrieveConnection: featureNotAvailableError, retrieveAllConnections: featureNotAvailableError, closeAllConnections: featureNotAvailableError, addUpgradeStatement: featureNotAvailableError, requestPermissions: featureNotAvailableError }, notAvailable);
}
/**

@@ -39,3 +27,17 @@ * Request Permissions

return new Promise(async (resolve) => {
console.log("$$$$ platform " + platform);
if (platform === "android") {
const androidPermissions = async () => {
console.log("$$$$ going to ask for permissions " + platform);
try {
await sqlitePlugin.requestPermissions();
return { result: true };
}
catch (e) {
console.log("Error requesting permissions " + e);
return { result: false,
message: "Error requesting permissions " + e };
}
};
let permissionsListener = null;
permissionsListener = sqlitePlugin.addListener('androidPermissionsRequest', async (e) => {

@@ -57,9 +59,6 @@ if (e.permissionGranted === 0) {

});
}, []);
}, [platform, sqlitePlugin]);
const echo = useCallback(async (value) => {
const r = await mSQLite.echo(value);
if (r) {
if (typeof r.value != 'undefined') {
return r;
}
if (value) {
return { value: value };
}

@@ -70,2 +69,5 @@ else {

}, []);
const getPlatform = useCallback(async () => {
return { platform: platform };
}, [platform]);
/**

@@ -79,3 +81,3 @@ * Create a Connection to Database

const createConnection = useCallback(async (dbName, encrypted, mode, version) => {
if (typeof dbName === 'undefined') {
if (dbName == null || dbName.length === 0) {
return { result: false,

@@ -93,3 +95,3 @@ message: 'Must provide a database name' };

return null;
}, []);
}, [mSQLite]);
/**

@@ -110,3 +112,3 @@ * Close the Connection to the Database

return { result: false, message: "Must provide a database name" };
}, []);
}, [mSQLite]);
/**

@@ -125,3 +127,3 @@ * Retrieve a Connection to the Database

return { result: false, message: "Must provide a database name" };
}, []);
}, [mSQLite]);
/**

@@ -133,3 +135,2 @@ * Retrieve all Connections to Databases

const r = await mSQLite.retrieveAllConnections();
var ret = {};
if (r) {

@@ -139,3 +140,3 @@ return r;

return null;
}, []);
}, [mSQLite]);
/**

@@ -153,3 +154,3 @@ * Close All Connections to Databases

return { result: false, message: "Error in closeConnection" };
}, []);
}, [mSQLite]);
/**

@@ -187,7 +188,12 @@ * Add the upgrade Statement for database version upgrading

}
}, []);
return { echo, createConnection, closeConnection, retrieveConnection,
retrieveAllConnections, closeAllConnections,
addUpgradeStatement, requestPermissions, isAvailable: true };
}
}, [mSQLite]);
if (!availableFeaturesN.useSQLite) {
return Object.assign({ echo: featureNotAvailableError, getPlatform: featureNotAvailableError, createConnection: featureNotAvailableError, closeConnection: featureNotAvailableError, retrieveConnection: featureNotAvailableError, retrieveAllConnections: featureNotAvailableError, closeAllConnections: featureNotAvailableError, addUpgradeStatement: featureNotAvailableError, requestPermissions: featureNotAvailableError }, notAvailable);
}
else {
return { echo, getPlatform, createConnection, closeConnection,
retrieveConnection, retrieveAllConnections, closeAllConnections,
addUpgradeStatement, requestPermissions, isAvailable: true };
}
};
//# sourceMappingURL=useSQLite.js.map
declare const featureMap: {
CapacitorSQLite: {
echo: {
web: boolean;
ios: boolean;
android: boolean;
electron: boolean;
};
createConnection: {
web: boolean;
ios: boolean;
android: boolean;
electron: boolean;
};
useSQLite: {

@@ -16,0 +4,0 @@ web: boolean;

@@ -11,4 +11,2 @@ import { Capacitor } from '@capacitor/core';

CapacitorSQLite: {
echo: Object.assign(Object.assign({}, allTrue), { web: false }),
createConnection: Object.assign(Object.assign({}, allTrue), { web: false }),
useSQLite: Object.assign(Object.assign({}, allTrue), { web: false }),

@@ -15,0 +13,0 @@ }

@@ -13,2 +13,3 @@ <p align="center"><br><img src="https://user-images.githubusercontent.com/236501/85893648-1c92e880-b7a8-11ea-926d-95355b8175c7.png" width="128" height="128" /></p>

* [`echo(...)`](#echo)
* [`getPlatform()`](#getplatform)
* [`addUpgradeStatement(...)`](#addupgradestatement)

@@ -51,2 +52,17 @@ * [`createConnection(...)`](#createconnection)

### getPlatform()
```typescript
getPlatform() => Promise<{ platform: string; }>
```
Get platform
**Returns:** <code>Promise&lt;{ platform: string; }&gt;</code>
**Since:** 1.0.0 refactor
--------------------
### addUpgradeStatement(...)

@@ -53,0 +69,0 @@

{
"name": "react-sqlite-hook",
"version": "1.0.0-alpha.2",
"version": "1.0.0-alpha.3",
"description": "React Hook for @Capacitor-community/sqlite plugin",

@@ -27,3 +27,3 @@ "repository": {

"build-old": "node scripts/build.js",
"docgen": "docgen --api ISQLiteHook --output-readme docs/APIHook.md",
"docgen": "docgen --api SQLiteHook --output-readme docs/APIHook.md",
"test": "jest"

@@ -30,0 +30,0 @@ },

@@ -43,2 +43,154 @@ <p align="center"><br><img src="https://avatars3.githubusercontent.com/u/16580653?v=4" width="128" height="128" /></p>

- in the project `app.tsx` file import the sqlite hook
```ts
import { useSQLite } from 'react-sqlite-hook/dist';
...
export let sqlite: any;
const App: React.FC = () => {
// to use the hook as a singleton
const {echo, getPlatform, createConnection, closeConnection,
retrieveConnection, retrieveAllConnections, closeAllConnections,
addUpgradeStatement, requestPermissions,
isAvailable} = useSQLite();
sqlite = {echo: echo, getPlatform: getPlatform,
createConnection: createConnection,
closeConnection: closeConnection,
retrieveConnection: retrieveConnection,
retrieveAllConnections: retrieveAllConnections,
closeAllConnections: closeAllConnections,
addUpgradeStatement: addUpgradeStatement,
requestPermissions: requestPermissions,
isAvailable:isAvailable};
...
return (
...
)
};
export default App;
```
- in a project component
```ts
...
import { sqlite } from '../App';
import { SQLiteDBConnection, Result } from 'react-sqlite-hook/dist';
const NoEncryption: React.FC = () => {
const [log, setLog] = useState<string[]>([]);
useEffect( () => {
const testDatabaseNoEncryption = async (): Promise<Boolean> => {
setLog((log) => log.concat("* Starting testDatabaseNoEncryption *\n"));
// test the plugin with echo
let res: any = await sqlite.echo("Hello from echo");
if(res.value !== "Hello from echo") return false;
setLog((log) => log.concat("> Echo successful\n"));
// create a connection for testNew
res = await sqlite.createConnection("testNew");
if(res == null ) return false;
if((Object.keys(res)).includes("result") && !res.result) return false;
setLog((log) => log.concat("> createConnection " +
" 'testNew' successful\n"));
let db: SQLiteDBConnection = res;
// open testNew
res = await db.open();
if(!res.result) return false;
setLog((log) => log.concat("> open 'testNew' successful\n"));
// Drop tables if exists
res = await db.execute(dropTablesTablesNoEncryption);
if(res.changes.changes !== 0 &&
res.changes.changes !== 1) return false;
setLog((log) => log.concat(" Execute1 successful\n"));
// Create tables
res = await db.execute(createTablesNoEncryption);
if(res.changes.changes !== 0 &&
res.changes.changes !== 1) return false;
setLog((log) => log.concat(" Execute2 successful\n"));
// Insert two users with execute method
res = await db.execute(importTwoUsers);
if(res.changes.changes !== 2) return false;
setLog((log) => log.concat(" Execute3 successful\n"));
// Select all Users
res = await db.query("SELECT * FROM users");
if(res.values.length !== 2 ||
res.values[0].name !== "Whiteley" ||
res.values[1].name !== "Jones") return false;
setLog((log) => log.concat(" Select1 successful\n"));
// add one user with statement and values
let sqlcmd = "INSERT INTO users (name,email,age) VALUES (?,?,?)";
let values: Array<any> = ["Simpson","Simpson@example.com",69];
res = await db.run(sqlcmd,values);
if(res.changes.changes !== 1 ||
res.changes.lastId !== 3) return false;
setLog((log) => log.concat(" Run1 successful\n"));
// add one user with statement
sqlcmd = `INSERT INTO users (name,email,age) VALUES `+
`("Brown","Brown@example.com",15)`;
res = await db.run(sqlcmd);
if(res.changes.changes !== 1 ||
res.changes.lastId !== 4) return false;
setLog((log) => log.concat(" Run2 successful\n"));
// Select all Users
res = await db.query("SELECT * FROM users");
if(res.values.length !== 4) return false;
setLog((log) => log.concat(" Select2 successful\n"));
// Select Users with age > 35
sqlcmd = "SELECT name,email,age FROM users WHERE age > ?";
values = ["35"];
res = await db.query(sqlcmd,values);
if(res.values.length !== 2) return false;
setLog((log) => log
.concat(" Select with filter on age successful\n"));
return true;
}
if(sqlite.isAvailable) {
testDatabaseNoEncryption().then(res => {
if(res) {
setLog((log) => log
.concat("\n* The set of tests was successful *\n"));
} else {
setLog((log) => log
.concat("\n* The set of tests failed *\n"));
}
});
} else {
sqlite.getPlatform().then((ret: { platform: string; }) => {
setLog((log) => log.concat("\n* Not available for " +
ret.platform + " platform *\n"));
});
}
}, []);
return (
<IonCard className="container-noencryption">
<IonCardContent>
<pre>
<p>{log}</p>
</pre>
</IonCardContent>
</IonCard>
);
};
```
## Contributors ✨

@@ -45,0 +197,0 @@

@@ -1,2 +0,2 @@

import { useCallback, useEffect } from 'react';
import { useCallback, useMemo } from 'react';
import { Capacitor, Plugins } from '@capacitor/core';

@@ -10,6 +10,7 @@ import { AvailableResult, notAvailable } from './util/models';

export { SQLiteDBConnection }
/**
* SQLite Hook Interface
*/
interface ISQLiteHook extends AvailableResult{
interface SQLiteHook extends AvailableResult {
/**

@@ -23,2 +24,8 @@ * Echo a value

/**
* Get platform
* @returns Promise<{platform: string}>
* @since 1.0.0 refactor
*/
getPlatform(): Promise<{platform: string}>;
/**
* Add an Upgrade Statement to Update Database Version

@@ -42,6 +49,6 @@ * @param dbName database name

createConnection(
database: string,
encrypted?: boolean,
mode?: string,
version?: number,
database: string,
encrypted?: boolean,
mode?: string,
version?: number,
): Promise<SQLiteDBConnection | Result | null>;

@@ -55,3 +62,3 @@ /**

retrieveConnection(
database: string,
database: string,
): Promise<SQLiteDBConnection | Result | null>;

@@ -83,4 +90,4 @@ /**

requestPermissions(): Promise<Result>;
}
interface MySet {

@@ -90,3 +97,3 @@ statement?: string;

}
interface VersionUpgrade {

@@ -98,45 +105,24 @@ fromVersion: number;

}
interface Result {
export interface Result {
result?: boolean;
message?: string
}
/**
* useSQLite Hook
*/
export function useSQLite(): ISQLiteHook {
export const useSQLite = (): SQLiteHook => {
const { CapacitorSQLite } = Plugins;
const platform = Capacitor.getPlatform();
const sqlitePlugin: any = CapacitorSQLite;
const mSQLite: SQLiteConnection = new SQLiteConnection(sqlitePlugin);
let permissionsListener: any = null;
const mSQLite = useMemo(() => {
return new SQLiteConnection(sqlitePlugin);
},[sqlitePlugin])
const availableFeaturesN = {
useSQLite: isFeatureAvailable('CapacitorSQLite', 'useSQLite')
}
const androidPermissions = async () => {
try {
await sqlitePlugin.requestPermissions();
return { result: true };
} catch (e) {
console.log("Error requesting permissions " + e);
return { result: false,
message: "Error requesting permissions " + e};
}
}
if (!availableFeaturesN.useSQLite) {
return {
echo: featureNotAvailableError,
createConnection: featureNotAvailableError,
closeConnection: featureNotAvailableError,
retrieveConnection: featureNotAvailableError,
retrieveAllConnections: featureNotAvailableError,
closeAllConnections: featureNotAvailableError,
addUpgradeStatement: featureNotAvailableError,
requestPermissions: featureNotAvailableError,
...notAvailable
};
}
/**

@@ -147,4 +133,16 @@ * Request Permissions

return new Promise(async (resolve) => {
console.log("$$$$ platform " + platform)
if(platform === "android") {
const androidPermissions = async () => {
console.log("$$$$ going to ask for permissions " + platform)
try {
await sqlitePlugin.requestPermissions();
return { result: true };
} catch (e) {
console.log("Error requesting permissions " + e);
return { result: false,
message: "Error requesting permissions " + e};
}
}
let permissionsListener: any = null;
permissionsListener = sqlitePlugin.addListener(

@@ -167,9 +165,7 @@ 'androidPermissionsRequest',async (e: any) => {

});
}, []);
}, [platform, sqlitePlugin]);
const echo = useCallback(async (value: string): Promise<any> => {
const r = await mSQLite.echo(value);
if(r) {
if( typeof r.value != 'undefined') {
return r;
}
if(value) {
return {value: value};
} else {

@@ -179,2 +175,7 @@ return {value: null};

}, []);
const getPlatform = useCallback(async (): Promise<any> => {
return {platform: platform};
}, [platform]);
/**

@@ -188,22 +189,22 @@ * Create a Connection to Database

const createConnection = useCallback(async (dbName: string,
encrypted?: boolean,
mode?: string,
version?: number)
: Promise<SQLiteDBConnection| Result | null> => {
if (typeof dbName === 'undefined') {
return { result: false,
message: 'Must provide a database name'};
}
const mDatabase: string = dbName;
const mVersion: number = version ? version : 1;
const mEncrypted: boolean = encrypted ? encrypted : false;
const mMode: string = mode ? mode : "no-encryption";
const r = await mSQLite.createConnection(
mDatabase, mEncrypted, mMode, mVersion);
encrypted?: boolean,
mode?: string,
version?: number)
: Promise<SQLiteDBConnection| Result | null> => {
if (dbName == null || dbName.length === 0) {
return { result: false,
message: 'Must provide a database name'};
}
const mDatabase: string = dbName;
const mVersion: number = version ? version : 1;
const mEncrypted: boolean = encrypted ? encrypted : false;
const mMode: string = mode ? mode : "no-encryption";
const r = await mSQLite.createConnection(
mDatabase, mEncrypted, mMode, mVersion);
if(r) {
return r;
}
return null;
}, []);
if(r) {
return r;
}
return null;
}, [mSQLite]);
/**

@@ -224,3 +225,3 @@ * Close the Connection to the Database

return {result: false, message: "Must provide a database name"};
}, []);
}, [mSQLite]);
/**

@@ -239,3 +240,3 @@ * Retrieve a Connection to the Database

return {result: false, message: "Must provide a database name"};
}, []);
}, [mSQLite]);
/**

@@ -247,8 +248,7 @@ * Retrieve all Connections to Databases

const r = await mSQLite.retrieveAllConnections();
var ret: any = {};
if(r) {
return r;
return r;
}
return null;
}, []);
}, [mSQLite]);
/**

@@ -266,3 +266,3 @@ * Close All Connections to Databases

return {result: false, message: "Error in closeConnection"};
}, []);
}, [mSQLite]);
/**

@@ -290,4 +290,4 @@ * Add the upgrade Statement for database version upgrading

.addUpgradeStatement(dbName, upgrade.fromVersion,
upgrade.toVersion, upgrade.statement,
upgrade.set)
upgrade.toVersion, upgrade.statement,
upgrade.set)
if(r) {

@@ -304,7 +304,24 @@ if( typeof r.result != 'undefined') {

}
}, [mSQLite]);
}, []);
return { echo, createConnection, closeConnection, retrieveConnection,
retrieveAllConnections, closeAllConnections,
addUpgradeStatement, requestPermissions, isAvailable: true };
}
if (!availableFeaturesN.useSQLite) {
return {
echo: featureNotAvailableError,
getPlatform: featureNotAvailableError,
createConnection: featureNotAvailableError,
closeConnection: featureNotAvailableError,
retrieveConnection: featureNotAvailableError,
retrieveAllConnections: featureNotAvailableError,
closeAllConnections: featureNotAvailableError,
addUpgradeStatement: featureNotAvailableError,
requestPermissions: featureNotAvailableError,
...notAvailable
};
} else {
return {echo, getPlatform, createConnection, closeConnection,
retrieveConnection, retrieveAllConnections, closeAllConnections,
addUpgradeStatement, requestPermissions, isAvailable: true};
}
}

@@ -13,4 +13,2 @@ import { Capacitor } from '@capacitor/core';

CapacitorSQLite: {
echo: {...allTrue, web: false},
createConnection: {...allTrue, web: false},
useSQLite: {...allTrue, web: false},

@@ -17,0 +15,0 @@ }

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc