Skip to content
Snippets Groups Projects
Commit 5947465c authored by Richard Fernando Heise Ferreira's avatar Richard Fernando Heise Ferreira
Browse files

Initial Commit

parent c95926dd
No related branches found
No related tags found
No related merge requests found
Showing
with 393 additions and 83 deletions
NODE_ENV=development
# db config
DB_HOST=localhost
DB_USER=postgres
DB_PASSWORD=postgres
DB_NAME=templatedb
DB_PORT=5432
DB_URL=postgresql://${DB_USER}:${DB_PASSWORD}@${DB_HOST}:${DB_PORT}/${DB_NAME}
# secret
APP_SECRET=0crebI8PUWwj9E+GRzIGpBt64MwY9ufkBzBkYSH2v+Y=
\ No newline at end of file
# deps
node_modules/
.env
{
"trailingComma": "es5",
"tabWidth": 2,
"semi": false,
"singleQuote": true,
"jsxSingleQuote": true,
"printWidth": 70,
"arrowParens": "always",
"bracketSpacing": true,
"bracketSameLine": false,
"useTabs": false
}
\ No newline at end of file
# Backend-MECRED
## Running for dev
New backend for MECRED
## Getting started
1. install docker
https://docs.docker.com/engine/install/ubuntu/
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
2. Install bun
https://bun.sh/docs/installation
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
3. To install dependencies:
```sh
bun install
```
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
4. Get the container up and running:
```sh
docker compose up
cp .env.example .env
```
5. set dev db
```
cd existing_repo
git remote add origin https://gitlab.c3sl.ufpr.br/mecred/backend-mecred.git
git branch -M main
git push -uf origin main
bun db:migrate
bun db:seed
```
## Integrate with your tools
- [ ] [Set up project integrations](https://gitlab.c3sl.ufpr.br/mecred/backend-mecred/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License
For open source projects, say how it is licensed.
6. Run dev server:
```sh
bun run dev
```
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
7. open http://localhost:3000
bun.lockb 0 → 100755
File added
preload = ["./src/preload.ts"]
loglevel = "debug"
\ No newline at end of file
services:
db:
image: postgres
restart: always
environment:
POSTGRES_DB: templatedb
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
ports:
- "5432:5432"
networks:
- tag_network
volumes:
- postgres_data:/var/lib/postgresql/data
volumes:
postgres_data:
networks:
tag_network:
import { defineConfig, type Config } from 'drizzle-kit'
import env from '@/env'
export default defineConfig({
schema: './src/db/schema/index.ts',
out: './src/db/migrations',
dialect: 'postgresql',
dbCredentials: {
url: env.DB_URL,
},
verbose: true,
strict: true,
}) satisfies Config
import globals from 'globals'
import pluginJs from '@eslint/js'
import tseslint from 'typescript-eslint'
import prettierEslint from 'eslint-config-prettier'
export default [
{ files: ['**/*.{js,mjs,cjs,ts}'] },
{ languageOptions: { globals: globals.browser } },
pluginJs.configs.recommended,
...tseslint.configs.recommended,
prettierEslint,
]
{
"name": "hono-backend",
"scripts": {
"dev": "bun run --watch src/index.ts",
"db:generate": "drizzle-kit generate",
"db:migrate": "cross-env DB_MIGRATING=true bun run src/db/migrate.ts",
"db:seed": "cross-env DB_SEEDING=true bun run src/db/seed.ts",
"db:studio": "drizzle-kit studio"
},
"dependencies": {
"@hono/zod-validator": "^0.2.2",
"dotenv": "^16.4.5",
"dotenv-expand": "^11.0.6",
"drizzle-orm": "^0.31.2",
"drizzle-zod": "^0.5.1",
"hono": "^4.4.8",
"postgres": "^3.4.4",
"reflect-metadata": "^0.2.2",
"typedi": "^0.10.0",
"zod": "^3.23.8"
},
"devDependencies": {
"@eslint/js": "^9.5.0",
"@types/bun": "latest",
"cross-env": "^7.0.3",
"drizzle-kit": "^0.22.7",
"eslint": "9.x",
"eslint-config-prettier": "^9.1.0",
"globals": "^15.6.0",
"prettier": "^3.3.2",
"typescript-eslint": "^7.14.1"
}
}
\ No newline at end of file
import { drizzle } from 'drizzle-orm/postgres-js'
import postgres from 'postgres'
import * as schema from '@/db/schema'
import env from '@/env'
export const connection = postgres(env.DB_URL, {
max: env.DB_MIGRATING || env.DB_SEEDING ? 1 : undefined,
onnotice: env.DB_SEEDING ? () => {} : undefined,
})
export const db = drizzle(connection, {
schema,
logger: true,
})
export type db = typeof db
export default db
import { migrate } from 'drizzle-orm/postgres-js/migrator'
import config from '$/drizzle.config'
import { db, connection } from '@/db'
import env from '@/env'
if (!env.DB_MIGRATING) {
throw new Error(
'You must set DB_MIGRATING to "true" when migrating'
)
}
await migrate(db, { migrationsFolder: config.out! })
await connection.end()
CREATE TABLE IF NOT EXISTS "user" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"username" varchar NOT NULL,
"password" varchar NOT NULL,
"name" varchar NOT NULL,
CONSTRAINT "user_username_unique" UNIQUE("username")
);
{
"id": "4cf89ad7-1672-440b-b964-dad35de18ec8",
"prevId": "00000000-0000-0000-0000-000000000000",
"version": "7",
"dialect": "postgresql",
"tables": {
"public.user": {
"name": "user",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "uuid",
"primaryKey": true,
"notNull": true,
"default": "gen_random_uuid()"
},
"username": {
"name": "username",
"type": "varchar",
"primaryKey": false,
"notNull": true
},
"password": {
"name": "password",
"type": "varchar",
"primaryKey": false,
"notNull": true
},
"name": {
"name": "name",
"type": "varchar",
"primaryKey": false,
"notNull": true
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {
"user_username_unique": {
"name": "user_username_unique",
"nullsNotDistinct": false,
"columns": [
"username"
]
}
}
}
},
"enums": {},
"schemas": {},
"_meta": {
"columns": {},
"schemas": {},
"tables": {}
}
}
\ No newline at end of file
{
"version": "7",
"dialect": "postgresql",
"entries": [
{
"idx": 0,
"version": "7",
"when": 1719362169477,
"tag": "0000_aspiring_frightful_four",
"breakpoints": true
}
]
}
\ No newline at end of file
import type { z } from 'zod'
import { userSchemas, type UserModel } from '../schema/user.model'
export function hashPassword(pass: UserModel['password']) {
return Bun.password.hashSync(pass, {
memoryCost: 4,
timeCost: 3,
algorithm: 'argon2id',
})
}
export function verifyPassword(
pass: UserModel['password'],
hash: UserModel['password']
) {
return Bun.password.verifySync(pass, hash)
}
export const authSchema = userSchemas.userModelSchema.pick({
username: true,
password: true,
})
export const authPayload = userSchemas.userModelSchema.pick({
id: true,
username: true,
})
export type AuthPayload = z.infer<typeof authPayload>
export type AuthInput = z.infer<typeof authSchema>
import { Service } from 'typedi'
import db from '@/db'
import userTable, {
userSchemas,
type UserInput,
type UserModel,
} from '../schema/user.model'
import { z } from 'zod'
import { eq } from 'drizzle-orm'
@Service()
export class UserRepo {
async findMany(): Promise<UserModel[]> {
return z.array(userSchemas.userModelSchema).parse(
await db.query.userTable.findMany({
limit: 100,
})
)
}
async findByUsername(
username: UserModel['username']
): Promise<UserModel | null> {
const user = await db.query.userTable.findFirst({
where: eq(userTable.username, username),
})
if (!user) return null
return userSchemas.userModelSchema.parse(user)
}
async create(user: UserInput, tx?: db): Promise<UserModel> {
const repo = tx ?? db
const [ret] = await repo
.insert(userTable)
.values(user)
.returning()
return userSchemas.userModelSchema.parse(ret)
}
async createMany(
users: UserInput[],
tx?: db
): Promise<UserModel[]> {
const repo = tx ?? db
return z
.array(userSchemas.userModelSchema)
.parse(await repo.insert(userTable).values(users).returning())
}
async uploadUsers(users: UserInput[]): Promise<UserModel[]> {
return await db.transaction(async (tx) => {
return z
.array(userSchemas.userModelSchema)
.parse(await tx.insert(userTable).values(users).returning())
})
}
}
import userTable from './user.model'
export { userTable }
export const tables = [userTable]
import { pgTable, uuid, varchar } from 'drizzle-orm/pg-core'
import { createInsertSchema, createSelectSchema } from 'drizzle-zod'
import { z } from 'zod'
const userTable = pgTable('user', {
id: uuid('id').primaryKey().defaultRandom(),
username: varchar('username').unique().notNull(),
password: varchar('password').notNull(),
name: varchar('name').notNull(),
})
const userInputSchema = createInsertSchema(userTable)
const userModelSchema = createSelectSchema(userTable)
const userDtoSchema = createSelectSchema(userTable).omit({
password: true,
})
export type UserInput = z.infer<typeof userInputSchema>
export type UserModel = z.infer<typeof userModelSchema>
export type UserDto = z.infer<typeof userDtoSchema>
export const userSchemas = {
userInputSchema,
userModelSchema,
userDtoSchema,
}
export default userTable
import env from '@/env'
import { connection, db } from '@/db'
import { Table, getTableName, sql } from 'drizzle-orm'
import * as schema from '@/db/schema'
import * as seeds from '@/db/seeds'
if (!env.DB_SEEDING) {
throw new Error('You must sed DB_SEEDING to "true" when seeding')
}
async function resetTable(db: db, table: Table) {
return db.execute(
sql.raw(
`TRUNCATE TABLE "${getTableName(table)}" RESTART IDENTITY CASCADE`
)
)
}
for (const table of schema.tables) {
await resetTable(db, table)
}
await seeds.userSeed(db)
await connection.end()
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment