Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(adapters): Add Drizzle #587

Merged
Merged
Show file tree
Hide file tree
Changes from 24 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/nasty-meals-fetch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@shopify/shopify-app-session-storage-drizzle': major
---

Initial release of @shopify/shopify-app-session-storage-drizzle
15 changes: 15 additions & 0 deletions loom.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,21 @@ function configureProjects(projects: Config.InitialProjectOptions[]) {
return acc.concat(forkRemixProject(project));
}

/*
* drizzle-orm is a special case because it seems to be ESM-only, so we need jest to run it through babel for the
* tests to work.
*/

if (
typeof project !== 'string' &&
project.displayName === 'shopify-app-session-storage-drizzle'
) {
project.transformIgnorePatterns = [
...(project.transformIgnorePatterns ?? []),
'node_modules/(?!drizzle-orm)',
];
}

return acc.concat(project);
}, [] as Config.InitialProjectOptions[]);
}
Expand Down
3 changes: 3 additions & 0 deletions packages/shopify-app-session-storage-drizzle/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
node_modules
# Keep environment variables out of version control
.env
7 changes: 7 additions & 0 deletions packages/shopify-app-session-storage-drizzle/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# @shopify/shopify-app-session-storage-drizzle

## 1.0.0

### Major Changes

- Initial release of @shopify/shopify-app-session-storage-drizzle
9 changes: 9 additions & 0 deletions packages/shopify-app-session-storage-drizzle/LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
MIT License

Copyright (c) 2024-present, Shopify Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
58 changes: 58 additions & 0 deletions packages/shopify-app-session-storage-drizzle/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# Session Storage Adapters for Drizzle

This package implements the `SessionStorage` interface that works with an instance of [Drizzle](https://orm.drizzle.team).

There are 3 adapters for Drizzle: `DrizzleSessionStoragePostgres`, `DrizzleSessionStorageSQLite` and `DrizzleSessionStorageMySQL`.

Session storage for Drizzle requires a `schema.ts` with a `session` table with at-least the columns as in the example. Make sure to create `session` table and apply changes to the database before using this pakacge.

## Example with SQLite

```ts
import {sqliteTable, text, integer, blob} from 'drizzle-orm/sqlite-core';

export const sessionTable = sqliteTable('session', {
id: text('id').primaryKey(),
shop: text('shop').notNull(),
state: text('state').notNull(),
isOnline: integer('isOnline', {mode: 'boolean'}).notNull().default(false),
scope: text('scope'),
expires: text('expires'),
accessToken: text('accessToken'),
userId: blob('userId', {mode: 'bigint'}),
});
```

You can then instantiate and use `DrizzleSessionStorageSQLite` like so:

```ts
import {shopifyApp} from '@shopify/shopify-app-express';
import {DrizzleSessionStorageSQLite} from '@shopify/shopify-app-session-storage-drizzle';

import {db} from './db.server';
paulomarg marked this conversation as resolved.
Show resolved Hide resolved
import {sessionTable} from './schema';

const storage = new DrizzleSessionStorageSQLite(db, sessionTable);

const shopify = shopifyApp({
sessionStorage: storage,
// ...
});
```

## Drizzle Setup

In the example above the file `db.server.ts` should import your database client, drizzle schema and export `db` that you can pass to the storage adapter:

```ts
import {drizzle} from 'drizzle-orm/libsql';
import {createClient} from '@libsql/client';

import * as schema from './schema';

export const client = createClient({
url: 'file:./dev.db',
});

export const db = drizzle(client, {schema});
```
27 changes: 27 additions & 0 deletions packages/shopify-app-session-storage-drizzle/loom.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import {createPackage, createProjectPlugin} from '@shopify/loom';
import {buildLibrary} from '@shopify/loom-plugin-build-library';

export default createPackage((pkg) => {
pkg.entry({root: './src/drizzle.ts'});
pkg.use(
buildLibrary({
// Required. A browserslist string for specifying your target output.
// Use browser targets (e.g. `'defaults'`) if your package targets the browser,
// node targets (e.g. `'node 12.22'`) if your package targets node
// or both (e.g.`'defaults, node 12.22'`) if your package targets both
targets: 'node 16',
// Optional. Defaults to false. Defines if commonjs outputs should be generated.
commonjs: true,
// Optional. Defaults to false. Defines if esmodules outputs should be generated.
esmodules: false,
// Optional. Defaults to false. Defines if esnext outputs should be generated.
esnext: false,
// Optional. Defaults to true. Defines if entrypoints should be written at
// the root of the repository. You can disable this if you have a single
// entrypoint or if your package uses the `exports` key in package.json
rootEntrypoints: false,
// Optional. Defaults to 'node'. Defines if the jest environment should be 'node' or 'jsdom'.
jestTestEnvironment: 'node',
}),
);
});
62 changes: 62 additions & 0 deletions packages/shopify-app-session-storage-drizzle/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
{
"name": "@shopify/shopify-app-session-storage-drizzle",
"version": "1.0.0",
"description": "Shopify App Session Storage for Drizzle",
"repository": {
"type": "git",
"url": "git+https://github.com/Shopify/shopify-app-js.git"
},
"bugs": {
"url": "https://github.com/Shopify/shopify-app-js/issues"
},
"homepage": "https://github.com/Shopify/shopify-app-js/tree/main/packages/shopify-app-session-storage-drizzle",
"author": "Shopify Inc.",
"license": "MIT",
"main": "./build/cjs/drizzle.js",
"types": "./build/ts/drizzle.d.ts",
"scripts": {},
"publishConfig": {
"access": "public"
},
"keywords": [
"shopify",
"node",
"app",
"graphql",
"rest",
"webhook",
"Admin API",
"Storefront API",
"session storage",
"Drizzle"
],
"dependencies": {
"tslib": "^2.6.2"
},
"peerDependencies": {
"@shopify/shopify-api": "^9.3.2",
"@shopify/shopify-app-session-storage": "^2.1.1",
"drizzle-orm": "^0.29.3"
},
"devDependencies": {
"@libsql/client": "^0.4.0-pre.7",
"@shopify/eslint-plugin": "^42.1.0",
"@shopify/prettier-config": "^1.1.2",
"@shopify/shopify-app-session-storage-test-utils": "^2.0.1",
"better-sqlite3": "^9.3.0",
"drizzle-kit": "^0.20.12",
"drizzle-orm": "^0.29.3",
"eslint": "^8.55.0",
"eslint-plugin-prettier": "^4.2.1",
"mysql2": "^3.9.1",
"pg": "^8.11.3",
"prettier": "^2.8.7",
"typescript": "4.9.5"
},
"files": [
"build/*",
"!bundle/*",
"!tsconfig.tsbuildinfo",
"!node_modules"
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import * as child_process from 'child_process';
import {promisify} from 'util';

import mysql2 from 'mysql2/promise';
import {
batteryOfTests,
poll,
} from '@shopify/shopify-app-session-storage-test-utils';
import {
mysqlTable,
text,
boolean,
timestamp,
bigint,
varchar,
} from 'drizzle-orm/mysql-core';
import {drizzle} from 'drizzle-orm/mysql2';

import {DrizzleSessionStorageMySQL} from '../adapters/drizzle-mysql.adapter';

const exec = promisify(child_process.exec);

const dbConfig = {
host: 'localhost',
user: 'root',
password: 'passify#$',
database: 'shop&test',
port: 3307,
};

const sessionTable = mysqlTable('session', {
id: varchar('id', {length: 255}).primaryKey(),
shop: text('shop').notNull(),
state: text('state').notNull(),
isOnline: boolean('isOnline').default(false).notNull(),
scope: text('scope'),
expires: timestamp('expires', {mode: 'date'}),
accessToken: text('accessToken'),
userId: bigint('userId', {mode: 'number'}),
});

describe('DrizzleSessionStorageMySQL', () => {
let drizzleSessionStorage: DrizzleSessionStorageMySQL;
let containerId: string;
let connection: mysql2.Connection;

beforeAll(async () => {
const runCommand = await exec(
"podman run -d -e MYSQL_DATABASE='shop&test' -e MYSQL_USER='shop&fy' -e MYSQL_PASSWORD='passify#$' -e MYSQL_ROOT_PASSWORD='passify#$' -p 3307:3306 mysql:8-oracle",
{encoding: 'utf8'},
);

containerId = runCommand.stdout.trim();

await poll(
async () => {
try {
connection = await mysql2.createConnection(dbConfig);
} catch (_error) {
// console.error(_error);
return false;
}
return true;
},
{interval: 500, timeout: 20000},
);

await connection.query(`
CREATE TABLE IF NOT EXISTS \`session\` (
\`id\` varchar(255) NOT NULL,
\`shop\` text NOT NULL,
\`state\` text NOT NULL,
\`isOnline\` boolean NOT NULL DEFAULT false,
\`scope\` text,
\`expires\` timestamp NULL,
\`accessToken\` text,
\`userId\` bigint,
CONSTRAINT \`session_id\` PRIMARY KEY (\`id\`)
);
`);

const drizzleDb = drizzle(connection);

drizzleSessionStorage = new DrizzleSessionStorageMySQL(
drizzleDb,
sessionTable,
);
});

afterAll(async () => {
if (connection) {
await connection.end();
}

await exec(`podman rm -f ${containerId}`);
});

batteryOfTests(async () => drizzleSessionStorage);
});
Loading
Loading