Skip to content

Commit

Permalink
Merge pull request #303 from palmaresHQ:fix-tool-issues
Browse files Browse the repository at this point in the history
fix template and issues with sequelize
  • Loading branch information
nicolasmelo1 authored Nov 25, 2024
2 parents f06f2c5 + b1b09b4 commit a10402f
Show file tree
Hide file tree
Showing 27 changed files with 382 additions and 41 deletions.
12 changes: 12 additions & 0 deletions .changeset/perfect-wolves-walk.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
'@palmares/sequelize-engine': patch
'@palmares/drizzle-engine': patch
'@palmares/databases': patch
'@palmares/node-std': patch
'@palmares/core': patch
'palmares': patch
---

- Sequelize package
- Fix small issue to allow empty migration files
- Fix typings on Sequelize Engine
3 changes: 2 additions & 1 deletion bin/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,8 @@ const cpaDomain = domain('palmares', '', {
},
handler: async (args) => {
// @ts-ignore Trust me bro
const basePath = import.meta.dirname;
const basePath: string = import.meta.dirname || std.files.dirname(std.files.getFileURLToPath(import.meta.url));

const fullPath = await std.files.join(basePath, '..', 'templates');
const allApps = await std.files.readDirectory(fullPath);
const commandLineArgs = args.commandLineArgs as ExtractCommandsType<typeof cpaDomain, 'new'>;
Expand Down
3 changes: 2 additions & 1 deletion libs/drizzle-engine/src/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ export const models = adapterModels({

afterModelsTranslation: async (engine, models): Promise<[string, any][]> => {
let fileContent = '';
const [cwd, directoryName] = await Promise.all([std.os.cwd(), std.files.dirname(engine.instance.output)]);
const cwd = await std.os.cwd();
const directoryName = std.files.dirname(engine.instance.output);
const [folderName, locationToRequire] = await Promise.all([
std.files.join(cwd, directoryName),
std.files.join(cwd, engine.instance.output)
Expand Down
8 changes: 6 additions & 2 deletions libs/node-std/src/interfaces/files.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { access, appendFile, constants, mkdir, readFile, readdir, rm, writeFile } from 'fs';
import { basename, dirname, join, relative } from 'path';
import { env } from 'process';
import { pathToFileURL } from 'url';
import { fileURLToPath, pathToFileURL } from 'url';

import type { FilesAndFolders } from '@palmares/core';

Expand Down Expand Up @@ -43,6 +43,10 @@ export class FilesAndFoldersNode implements FilesAndFolders {
});
}

getFileURLToPath(path: string) {
return fileURLToPath(path);
}

getPathToFileURL(path: string) {
return pathToFileURL(path).pathname;
}
Expand All @@ -65,7 +69,7 @@ export class FilesAndFoldersNode implements FilesAndFolders {
});
}

async dirname(path: string): Promise<string> {
dirname(path: string): string {
return dirname(path);
}

Expand Down
19 changes: 14 additions & 5 deletions libs/sequelize-engine/src/types.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
import type { InitializedModelsType, ModelFields, Model as PalmaresModel, fields } from '@palmares/databases';
import type { IndexesOptions, Model, ModelAttributeColumnOptions, ModelCtor, ModelStatic } from 'sequelize';
import type { InferModel, InitializedModelsType, fields } from '@palmares/databases';
import type {
CreationOptional,
IndexesOptions,
Model,
ModelAttributeColumnOptions,
ModelCtor,
ModelStatic
} from 'sequelize';

export type IndexesToAddOnNextIterationType = {
tableName: string;
Expand Down Expand Up @@ -43,9 +50,11 @@ export type RelatedModelToEvaluateAfterType = {
[key: string]: RelatedFieldsToEvaluateType[];
};

export type SequelizeModel<TTypeModel extends InstanceType<ReturnType<typeof PalmaresModel>>> = ModelCtor<
Model<ModelFields<TTypeModel>>
>;
export type SequelizeModel<TTypeModel, TFieldsOfModel = InferModel<TTypeModel, 'create'>> = typeof Model<{
[TKey in keyof TFieldsOfModel]: TFieldsOfModel[TKey] extends undefined
? CreationOptional<NonNullable<TFieldsOfModel[TKey]>>
: NonNullable<TFieldsOfModel[TKey]>;
}>;

export type TranslatedFieldToEvaluateAfterType = {
fieldAttributes: ModelAttributeColumnOptions<Model<any, any>>;
Expand Down
3 changes: 2 additions & 1 deletion packages/core/src/std-adapter/files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export interface FilesAndFolders {
* that only allows dynamic imports to occur if the path is a URL with file://
*/
getPathToFileURL: (path: string) => string;
getFileURLToPath: (path: string) => string;

/**
* When the path is a simple string work normally, if the path is an array of strings, join
Expand All @@ -38,7 +39,7 @@ export interface FilesAndFolders {
* the strings with .join() and then work normally
*/
removeFile: (path: string) => Promise<void>;
dirname: (path: string) => Promise<string>;
dirname: (path: string) => string;
/**
* When the path is a simple string work normally, if the path is an array of strings, join
* the strings with .join() and then work normally
Expand Down
6 changes: 3 additions & 3 deletions packages/core/src/std/std.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ const std = {
return getDefaultStd().files.appendFile(path, content);
},
getPathToFileURL: (path: string) => getDefaultStd().files.getPathToFileURL(path),
getFileURLToPath: (path: string) => getDefaultStd().files.getFileURLToPath(path),
writeFile: async (path: string | string[], content: string) => {
if (Array.isArray(path)) path = await getDefaultStd().files.join(...path);
return getDefaultStd().files.writeFile(path, content);
Expand All @@ -58,9 +59,8 @@ const std = {
if (!exists) throw new FileOrDirectoryDoesNotExistError(path);
return getDefaultStd().files.removeFile(path);
},
dirname: async (path: string | string[]) => {
if (Array.isArray(path)) path = await getDefaultStd().files.join(...path);
return await getDefaultStd().files.dirname(path);
dirname: (path: string) => {
return getDefaultStd().files.dirname(path);
},
basename: async (path: string | string[]) => {
if (Array.isArray(path)) path = await getDefaultStd().files.join(...path);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { describe } from '@palmares/tests';
import { Company, ProfileType, User } from './models';

import type JestTestAdapter from '@palmares/jest-tests';
import type { SequelizeModel } from '@palmares/sequelize-engine';
//import { QuerySet } from 'packages/databases/dist/src/queries/queryset';

describe<JestTestAdapter>('sequelize models', ({ test }) => {
Expand Down
19 changes: 5 additions & 14 deletions packages/databases/__tests__/src/standalone/sequelize/models.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,18 @@
import {
Model,
define,
auto,
char,
text,
bool,
ON_DELETE,
foreignKey
} from '@palmares/databases';
import { Model, ON_DELETE, auto, bool, char, define, foreignKey, text } from '@palmares/databases';

import type { ModelOptionsType } from '@palmares/databases'
import type { ModelOptionsType } from '@palmares/databases';

export class Company extends Model<Company>() {
fields = {
id: auto(),
name: char({ maxLen: 255 }),
slug: char({ maxLen: 255 }),
isActive: bool().default(true)
}
};

options = {
options = {
tableName: 'company'
} satisfies ModelOptionsType<Company> // We use satisfies here so we can still infer and you don't lose intellisense.
} satisfies ModelOptionsType<Company>; // We use satisfies here so we can still infer and you don't lose intellisense.
}

export const User = define('User', {
Expand Down
3 changes: 1 addition & 2 deletions packages/databases/src/engine/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,7 @@ export function databaseAdapter<
close: TFunctionClose;
transaction: TFunctionTransaction;
};
new: TFunctionNew;
} {
} & { new: TFunctionNew } {
class CustomDatabaseAdapter extends DatabaseAdapter<
ReturnType<Awaited<ReturnType<TFunctionNew>>[1]>['instance'],
TFieldsAdapter,
Expand Down
8 changes: 7 additions & 1 deletion packages/databases/src/migrations/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,12 +57,18 @@ export class Migrations {
const foundMigrations: FoundMigrationsFileType[] = [];
const promises: Promise<void>[] = this.domains.map(async (domain) => {
if (domain.getMigrations) {
let domainMigrations = await Promise.resolve(domain.getMigrations());
let domainMigrations: Record<string, MigrationFileType> | MigrationFileType[] = await Promise.resolve(
domain.getMigrations()
);
// eslint-disable-next-line ts/no-unnecessary-condition
if (typeof domainMigrations === 'object' && domainMigrations !== null)
domainMigrations = Object.values(domainMigrations);

for (const domainMigration of domainMigrations) {
// eslint-disable-next-line ts/no-unnecessary-condition
if (domainMigration === undefined) continue;
// eslint-disable-next-line ts/no-unnecessary-condition
if (domainMigration === null) continue;
foundMigrations.push({
domainPath: domain.path,
domainName: domain.name,
Expand Down
19 changes: 15 additions & 4 deletions packages/databases/templates/app/drizzle/database.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,24 @@ import Database from 'better-sqlite3';

import { Company, User } from './src/models';

// SQLITE database
const database = new Database('sqlite.db');
export const db = drizzleBetterSqlite3(database);

/**
* To use with postgres database uncomment the following lines
*/
// import 'dotenv/config';
// import { drizzle as drizzleNodePostgres } from '@palmares/drizzle-engine/node-postgres';
// export const db = drizzleNodePostgres(process.env.DATABASE_URL!);

const newEngine = DrizzleDatabaseAdapter.new({
output: './.drizzle/schema.ts',
type: 'better-sqlite3',
drizzle: drizzleBetterSqlite3(database)
drizzle: db
});

export const db = newEngine[1]().instance.instance;
const std = new NodeStd();

export default setDatabaseConfig({
databases: {
Expand All @@ -27,10 +36,12 @@ export default setDatabaseConfig({
locations: [
{
name: 'default',
path: import.meta.dirname,
// dirname and fileURLToPath is just for compatibility with older versions of Node.js
// Remove if you are using Node.js 20.0.0 or higher
path: import.meta.dirname || std.files.dirname(std.files.getFileURLToPath(import.meta.url)),
getMigrations: () => [],
getModels: () => [Company, User]
}
],
std: new NodeStd()
std
});
20 changes: 20 additions & 0 deletions packages/databases/templates/app/drizzle/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,14 @@ import '../database.config';

import { Company, User } from './models';

/**
* YOU CAN STILL USE DRIZZLE!
*
* Uncomment the following Lines of Code to query the database from Drizzle.
*/
// import { db } from '../database.config';
// import * as d from '../.drizzle/schema';

(async () => {
await Company.default.set((qs) =>
qs
Expand All @@ -27,4 +35,16 @@ import { Company, User } from './models';
isActive: true
})
);

const data = await User.default.get((qs) => qs.join(Company, 'company', (qs) => qs.where({ slug: 'evil-foo' })));

console.log('All users in your db:', data);

/**
* YOU CAN STILL USE DRIZZLE!
*
* Uncomment the following Lines of Code to query the database from Drizzle.
*/
// const dataFromDrizzle = await db.select().from(d.User)
// console.log('Hello from Drizzle Users:', dataFromDrizzle);
})();
16 changes: 10 additions & 6 deletions packages/databases/templates/app/drizzle/src/models.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,21 @@
// eslint-disable-next-line ts/ban-ts-comment
// @ts-nocheck
import { Model, ON_DELETE, auto, bool, char, define, foreignKey, text } from '@palmares/databases';
import { Model, ON_DELETE, auto, char, define, fields, foreignKey, text } from '@palmares/databases';

import type { ModelOptionsType } from '@palmares/databases';

export class Company extends Model<Company>() {
fields = {
id: auto(),
name: char({ maxLen: 255 }),
slug: char({ maxLen: 255 }),
isActive: bool().default(true)
id: fields.auto(),
name: fields.char({ maxLen: 255 }),
slug: fields.char({ maxLen: 255 }),
isActive: fields.bool().default(true)
};

options = {
tableName: 'company'
} satisfies ModelOptionsType<Company>; // We use satisfies here so we can still infer and you don't lose intellisense.
// We use satisfies here so we can still infer and you don't lose intellisense.
} satisfies ModelOptionsType<Company>;
}

export const User = define('User', {
Expand All @@ -30,5 +31,8 @@ export const User = define('User', {
relatedName: 'usersOfCompany',
onDelete: ON_DELETE.CASCADE
})
},
options: {
tableName: 'user'
}
});
2 changes: 1 addition & 1 deletion packages/databases/templates/app/drizzle/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"compilerOptions": {
"target": "ES6",
"module": "ES2015",
"module": "ES2020",
"moduleResolution": "bundler",
"lib": ["es6"],
"allowJs": true,
Expand Down
24 changes: 24 additions & 0 deletions packages/databases/templates/app/sequelize/$gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*

node_modules
dist
dist-ssr
*.local

# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
41 changes: 41 additions & 0 deletions packages/databases/templates/app/sequelize/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# The amazing ${appName}

This project was created using [@palmares/databases](https://www.npmjs.com/package/@palmares/databases) [Sequelize's](https://sequelize.org/docs/v6/) template.

## Getting started

1. Install the dependencies:

```bash
$ ${packageManager} install
```

2. Run the migrations

```bash
$ ${packageManager} run migrate
```

3. Run the application

```bash
$ ${packageManager} run dev
```

## Migrations

- Generate the migrations by running

```bash
$ ${packageManager} run makemigrations
```

- Run the migrations by running

```bash
$ ${packageManger} run migrate
```

## Learn More

To learn more reach out to [@palmares/databases](https://www.npmjs.com/package/@palmares/databases), you can see more links on the bottom of the page
12 changes: 12 additions & 0 deletions packages/databases/templates/app/sequelize/_eslint.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import globals from "globals";
import pluginJs from "@eslint/js";
import tseslint from "typescript-eslint";


/** @type {import('eslint').Linter.Config[]} */
export default [
{files: ["**/*.{js,mjs,cjs,ts}"]},
{languageOptions: { globals: globals.node }},
pluginJs.configs.recommended,
...tseslint.configs.recommended,
];
Loading

0 comments on commit a10402f

Please sign in to comment.