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 7 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
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) 2022-present, Shopify Inc.
paulomarg marked this conversation as resolved.
Show resolved Hide resolved

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.
37 changes: 37 additions & 0 deletions packages/shopify-app-session-storage-drizzle/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# Session Storage Adapter for Drizzle

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

Session storage for Drizzle requires a `schema.ts` with a Session table with at-least the following columns:

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

export const sessions = sqliteTable('sessions', {
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 `DrizzleSessionStorage` like so:

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

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

const storage = new DrizzleSessionStorage(db, sessions);

const shopify = shopifyApp({
sessionStorage: storage,
// ...
});
```
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',
}),
);
});
60 changes: 60 additions & 0 deletions packages/shopify-app-session-storage-drizzle/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
{
"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": {
"drizzle-orm": "^0.29.3",
paulomarg marked this conversation as resolved.
Show resolved Hide resolved
"tslib": "^2.6.2"
},
"peerDependencies": {
"@shopify/shopify-api": "^9.0.1",
"@shopify/shopify-app-session-storage": "^2.0.3"
},
"devDependencies": {
"@libsql/client": "^0.4.0-pre.7",
"@shopify/eslint-plugin": "^42.1.0",
"@shopify/prettier-config": "^1.1.2",
"@shopify/shopify-api": "^9.0.1",
"@shopify/shopify-app-session-storage": "^2.0.3",
"@shopify/shopify-app-session-storage-test-utils": "^1.0.3",
"drizzle-kit": "^0.20.12",
"eslint": "^8.55.0",
"eslint-plugin-prettier": "^4.2.1",
"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,8 @@
import fetchMock from 'jest-fetch-mock';

// Globally disable fetch requests so we don't risk making real ones
fetchMock.enableMocks();

beforeEach(() => {
fetchMock.mockReset();
});
81 changes: 81 additions & 0 deletions packages/shopify-app-session-storage-drizzle/src/drizzle.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import {Session} from '@shopify/shopify-api';
import {and, eq} from 'drizzle-orm';
import type {SessionStorage} from '@shopify/shopify-app-session-storage';

export class DrizzleSessionStorage implements SessionStorage {
constructor(
// Generated Types needed from the following (in user app)
// export const db = drizzle(client, { schema });
// sessionsTable could be sqliteTable, pgTable etc.
private db: any,
private sessionsTable: any,
) {
this.db = db;
this.sessionsTable = sessionsTable;
}

public async storeSession(session: Session): Promise<boolean> {
await this.db
.insert(this.sessionsTable)
.values(session)
.onConflictDoUpdate({
target: this.sessionsTable.id,
notrab marked this conversation as resolved.
Show resolved Hide resolved
set: session,
});

return true;
}

public async loadSession(id: string): Promise<Session | undefined> {
const row = await this.db.query.sessions.findFirst({
where(fields: any, operators: any) {
return operators.eq(fields.id, id);
},
});

if (!row) {
return undefined;
}

return this.databaseRowToSession(row);
}

public async deleteSession(id: string): Promise<boolean> {
const deletedSessionIds: {deletedId: string}[] = await this.db
.delete(this.sessionsTable)
.where(eq(this.sessionsTable.id, id))
.returning({deletedId: this.sessionsTable.id});

return deletedSessionIds.length > 0;
}

public async deleteSessions(ids: string[]): Promise<boolean> {
if (ids.length === 0) return true;

await this.db
.delete(this.sessionsTable)
.where(and(...ids.map((id) => eq(this.sessionsTable.id, id))));

return true;
}

public async findSessionsByShop(shop: string): Promise<Session[]> {
const sessions = await this.db.query.sessions.findMany({
where: (fields: any, operators: any) => {
return operators.eq(fields.shop, shop);
},
limit: 25,
orderBy(fields: any, operators: any) {
return operators.desc(fields.expires);
},
});

return sessions.map((row: any) => this.databaseRowToSession(row));
}

private databaseRowToSession(row: any): Session {
if (row.expires) row.expires = new Date(row.expires);

return Session.fromPropertyArray(Object.entries(row));
}
}
10 changes: 10 additions & 0 deletions packages/shopify-app-session-storage-drizzle/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"baseUrl": ".",
"outDir": "./build/ts",
"rootDir": "src"
},
"include": ["src/**/*.ts"],
"exclude": ["**/*.test.ts", "**/*.test.tsx", "**/test/*", "**/__tests__/*"]
}
1 change: 1 addition & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
{"path": "./packages/shopify-app-session-storage-mysql"},
{"path": "./packages/shopify-app-session-storage-postgresql"},
{"path": "./packages/shopify-app-session-storage-prisma"},
{"path": "./packages/shopify-app-session-storage-drizzle"},
{"path": "./packages/shopify-app-session-storage-redis"},
{"path": "./packages/shopify-app-session-storage-sqlite"},
{"path": "./packages/shopify-app-session-storage-kv"},
Expand Down
Loading