diff --git a/.env b/.env
index 25b8521..07dfd57 100644
--- a/.env
+++ b/.env
@@ -1,9 +1,6 @@
-POSTGRES_URI=postgres://postgres:admin@192.168.1.250:5432/postgres
-DB_HOST=192.168.1.250:5432
-DB_USER=postgres
-DB_PASSWORD=admin
-DB_DATABASE=postgres
-PORT=3001
+# POSTGRES_URI=postgres://postgres:admin@192.168.1.250:5432/postgres
+POSTGRES_URI=postgres://postgres:v1sq3vD5faXL@194.26.138.94:5432/estate
+PORT=3003
JWT_ACCESS_SECRET=aboba
JWT_REFRESH_SECRET=aboba
JWT_ACCESS_EXP_TIME=30d
diff --git a/.env.production b/.env.production
new file mode 100644
index 0000000..99290a7
--- /dev/null
+++ b/.env.production
@@ -0,0 +1,12 @@
+POSTGRES_URI=postgres://postgres:v1sq3vD5faXL@194.26.138.94:5432/estate
+PORT=3003
+JWT_ACCESS_SECRET=aboba
+JWT_REFRESH_SECRET=aboba
+JWT_ACCESS_EXP_TIME=30d
+JWT_REFRESH_EXP_TIME=30d
+NODE_ENV=development
+S3_REGION=ru-central1
+S3_ENDPOINT=https://storage.yandexcloud.net
+S3_ACCESS_KEY_ID=YCAJE7XefUV51hyi9GEdld8S3
+S3_ACCESS_KEY=YCPY__ni1vs95aDjhutAlF8xX0kg3XP6Lbj9PifZ
+S3_BUCKET=dult-faib-knac-fint
\ No newline at end of file
diff --git a/.gitignore b/.gitignore
index 87e5610..d93b324 100644
--- a/.gitignore
+++ b/.gitignore
@@ -33,6 +33,9 @@ yarn-error.log*
# vercel
.vercel
+dist
+.vscode
+
**/*.trace
**/*.zip
**/*.tar.gz
diff --git a/bun.build.ts b/bun.build.ts
new file mode 100644
index 0000000..1a23f11
--- /dev/null
+++ b/bun.build.ts
@@ -0,0 +1,31 @@
+import { $, Glob } from 'bun';
+import path from 'path';
+
+// Cross-platform directory removal
+if (process.platform === 'win32') {
+ // await $`cmd /c "rmdir /s /q dist"`;
+} else {
+ await $`rm -rf ./dist`;
+}
+
+// await Bun.build({
+// entrypoints: ["./src/index.ts"],
+// env: "inline",
+// target: "bun",
+// outdir: `./dist`,
+// minify: true,
+// });
+
+// Build all files in src
+for (const entrypoint of new Glob('./src/**/*.ts').scanSync()) {
+ const parts = entrypoint.split(path.sep);
+ const entrypointPath = path.join(...parts.slice(2, -1));
+
+ await Bun.build({
+ entrypoints: [entrypoint],
+ target: 'bun',
+ outdir: path.join('dist', entrypointPath),
+ env: 'inline',
+ minify: true,
+ });
+}
diff --git a/bun.config.ts b/bun.config.ts
deleted file mode 100644
index 53cdc8d..0000000
--- a/bun.config.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import { Glob } from 'bun';
-
-for (const entrypoint of new Glob('src/**/*.ts').scanSync())
- await Bun.build({
- entrypoints: [entrypoint],
- target: 'bun',
- outdir: './dist/' + entrypoint.split('\\').slice(1, -1).join('\\'),
- });
diff --git a/drizzle.config.ts b/drizzle.config.ts
index 8a4ec96..1d580d3 100644
--- a/drizzle.config.ts
+++ b/drizzle.config.ts
@@ -1,5 +1,7 @@
import { defineConfig } from 'drizzle-kit';
+console.log('POSTGRES_URI!', process.env.POSTGRES_URI!);
+
export default defineConfig({
dialect: 'postgresql',
schema: './src/db/schema/index.ts',
diff --git a/package.json b/package.json
index 4119a41..b78d3ab 100644
--- a/package.json
+++ b/package.json
@@ -4,7 +4,8 @@
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "bun --hot ./src",
- "push": "drizzle-kit push"
+ "push": "drizzle-kit push",
+ "build": "bun ./bun.build.ts"
},
"dependencies": {
"@aws-sdk/client-s3": "^3.709.0",
diff --git a/src/controllers/articles.ts b/src/controllers/articles.ts
index 84e6f43..96f1fc6 100644
--- a/src/controllers/articles.ts
+++ b/src/controllers/articles.ts
@@ -1,11 +1,16 @@
import Elysia, { t } from 'elysia';
-import { authMiddleware } from '../middlewares/auth';
-import { getAll, getOne, create, remove, update } from '../services/articles';
-import { Block } from '../types/article';
-import { getCount } from '../services/articles/getCount';
+import { authMiddleware } from '../middlewares/auth.ts';
+import {
+ getAll,
+ getOne,
+ create,
+ remove,
+ update,
+} from '../services/articles/index.ts';
+import { getCount } from '../services/articles/getCount.ts';
import { createInsertSchema, createSelectSchema } from 'drizzle-typebox';
-import { articlesTable } from '../db/schema';
-import { getDrafted } from '../services/articles/getDrafted';
+import { articlesTable } from '../db/schema/index.ts';
+import { getDrafted } from '../services/articles/getDrafted.ts';
const getArticle = createSelectSchema(articlesTable);
diff --git a/src/controllers/auth.ts b/src/controllers/auth.ts
index 22d0d08..5fc5c7e 100644
--- a/src/controllers/auth.ts
+++ b/src/controllers/auth.ts
@@ -3,7 +3,7 @@ import { authMiddleware } from '../middlewares/auth';
import { login, logout, refresh } from '../services/auth';
export const authController = new Elysia({ prefix: '/auth' })
- .post('/login', async ({ body, cookie }) => await login(body, cookie), {
+ .post('/login', async ({ body }) => await login(body), {
body: t.Object({
username: t.String(),
password: t.String({ minLength: 6 }),
@@ -16,16 +16,15 @@ export const authController = new Elysia({ prefix: '/auth' })
},
})
.use(authMiddleware)
- .get('/check', async (context) => {
- return {
- auth: 'adminId' in context && context.adminId,
- };
- })
+ .get('/check', async (context) => ({
+ auth: !!('adminId' in context && context.adminId),
+ }))
.get(
'/logout',
- async ({ cookie, adminId }) => await logout(cookie, adminId),
+ async ({ adminId, headers }) =>
+ await logout(adminId, headers.authorization),
{
- cookie: t.Cookie({ accessToken: t.String(), refreshToken: t.String() }),
+ // cookie: t.Cookie({ accessToken: t.String(), refreshToken: t.String() }),
adminId: t.String(),
response: {
200: t.Object({ success: t.Boolean() }),
@@ -33,6 +32,9 @@ export const authController = new Elysia({ prefix: '/auth' })
401: t.ObjectString({}),
500: t.ObjectString({}),
},
+ headers: t.Object({
+ authorization: t.String(),
+ }),
}
)
.get(
diff --git a/src/controllers/companies.ts b/src/controllers/companies.ts
index 2f46227..679a321 100644
--- a/src/controllers/companies.ts
+++ b/src/controllers/companies.ts
@@ -5,11 +5,11 @@ import {
create,
update,
remove,
-} from '../services/companies';
-import { authMiddleware } from '../middlewares/auth';
+} from '../services/companies/index.ts';
+import { authMiddleware } from '../middlewares/auth.ts';
import { createInsertSchema, createSelectSchema } from 'drizzle-typebox';
-import { companiesTable } from '../db/schema';
-import { getByCity } from '../services/companies/getByCity';
+import { companiesTable } from '../db/schema/index.ts';
+import { getByCity } from '../services/companies/getByCity.ts';
const createCompany = createInsertSchema(companiesTable);
diff --git a/src/controllers/mail.ts b/src/controllers/mail.ts
index 3283297..e0266b9 100644
--- a/src/controllers/mail.ts
+++ b/src/controllers/mail.ts
@@ -1,51 +1,69 @@
-import Elysia, { t } from 'elysia';
+import Elysia, { error, t } from 'elysia';
import nodemailer from 'nodemailer';
+import { db } from '../db';
+import { mailTable } from '../db/schema/mail';
+import { createInsertSchema } from 'drizzle-typebox';
+
+const createMailSchema = createInsertSchema(mailTable);
export const mailController = new Elysia({ prefix: '/mail' }).post(
'/',
async ({
headers: { referer },
- body: { email, fullname, phone, products },
+ body: { email, fullname, phone, products = [], request = '' },
}) => {
const url = new URL(referer);
- let transporter = nodemailer.createTransport({
- host: 'mail.netangels.ru',
- port: 587,
- secure: false, // true for 465, false for other ports
- auth: {
- user: 'test@graff.tech', // generated ethereal user
- pass: 'ZmL0pKiDFWUyCDMq', // generated ethereal password
- },
- });
+ try {
+ await db
+ .insert(mailTable)
+ .values({ email, fullname, phone, products, request, from: url.host });
- let info = await transporter.sendMail({
- from: email, // sender address
- to: 'info@graff.tech', // list of receivers
- subject: `Заявка с сайта ${url.host}`, // Subject line
- text: `
- Имя Фамилия: ${fullname}
- Email: ${email}
- Телефон: ${phone}
- Продукты: ${products.join(', ')}
- `, // plain text body
- html: `
-
Имя: ${fullname}
-
Email: ${email}
-
Телефон: ${phone}
-
Продукты: ${products.join(', ')}
-
`, // html body
- });
+ let transporter = nodemailer.createTransport({
+ host: 'mail.netangels.ru',
+ port: 587,
+ secure: false, // true for 465, false for other ports
+ auth: {
+ user: 'test@graff.tech', // generated ethereal user
+ pass: 'ZmL0pKiDFWUyCDMq', // generated ethereal password
+ },
+ });
- return info;
+ let info = await transporter.sendMail({
+ from: email, // sender address
+ to: 'info@graff.tech', // list of receivers
+ subject: `Заявка с сайта ${url.host}`, // Subject line
+ text: `
+ Имя Фамилия: ${fullname}
+ Email: ${email}
+ ${phone ? `Телефон: ${phone}` : ''}
+ ${
+ products && products.length > 0
+ ? 'Продукты: ' + products.join(', ')
+ : ''
+ }
+ `, // plain text body
+ html: `
+
Имя: ${fullname}
+
Email: ${email}
+ ${phone ? `
Телефон: ${phone}
` : ''}
+ ${
+ products && products.length > 0
+ ? '
Продукты: ' + products.join(', ') + '
'
+ : ''
+ }
+ ${request ? '
Текст заявки: ' + request + '
' : ''}
+
`, // html body
+ });
+
+ return info;
+ } catch (err) {
+ console.log((err as Error).message);
+ return error(500, { error: 'Internal Server Error' });
+ }
},
{
headers: t.Object({ referer: t.String() }),
- body: t.Object({
- fullname: t.String(),
- email: t.String({ format: 'email' }),
- phone: t.String(),
- products: t.Array(t.String()),
- }),
+ body: createMailSchema,
}
);
diff --git a/src/controllers/map.ts b/src/controllers/map.ts
new file mode 100644
index 0000000..008a5f2
--- /dev/null
+++ b/src/controllers/map.ts
@@ -0,0 +1,52 @@
+import { createInsertSchema, createSelectSchema } from 'drizzle-typebox';
+import Elysia, { t } from 'elysia';
+import { mapTable } from '../db/schema';
+import { getByCity } from '../services/map/getByCity';
+import { authMiddleware } from '../middlewares/auth';
+import { createMapPoint } from '../services/map/createMapPoint';
+import { updateMapPoint } from '../services/map/updateMapPoint';
+import { deleteMapPoint } from '../services/map/deleteMapPoint';
+
+const getMapPointsSchema = createSelectSchema(mapTable);
+
+const createMapPointSchema = createInsertSchema(mapTable);
+
+export const mapController = new Elysia({
+ prefix: '/map',
+})
+ .get('/', async ({ query: { city } }) => await getByCity(city), {
+ response: {
+ 200: t.Array(getMapPointsSchema),
+ 404: t.ObjectString({}),
+ 500: t.ObjectString({}),
+ },
+ query: t.Object({
+ city: t.String(),
+ }),
+ })
+ .use(authMiddleware)
+ .post('/', async ({ body }) => await createMapPoint(body), {
+ response: { 200: getMapPointsSchema, 500: t.ObjectString({}) },
+ body: createMapPointSchema,
+ })
+ .put(
+ '/:id',
+ async ({ body, params: { id } }) => await updateMapPoint(id, body),
+ {
+ response: {
+ 200: getMapPointsSchema,
+ 404: t.ObjectString({}),
+ 500: t.ObjectString({}),
+ },
+ params: t.Object({ id: t.String({ format: 'uuid' }) }),
+ body: createMapPointSchema,
+ }
+ )
+ .delete('/:id', async ({ params: { id } }) => await deleteMapPoint(id), {
+ response: {
+ 200: getMapPointsSchema,
+ 404: t.ObjectString({}),
+ 500: t.ObjectString({}),
+ },
+ params: t.Object({ id: t.String({ format: 'uuid' }) }),
+ });
diff --git a/src/controllers/mapVideos.ts b/src/controllers/mapVideos.ts
deleted file mode 100644
index b3bf5e0..0000000
--- a/src/controllers/mapVideos.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-import { getAll } from '../services/mapVideos/getAll';
-import { createInsertSchema, createSelectSchema } from 'drizzle-typebox';
-import Elysia, { t } from 'elysia';
-import { mapVideosTable } from '../db/schema';
-import { authMiddleware } from '../middlewares/auth';
-import { createMapVideo } from '../services/mapVideos/create';
-import { updateMapVideo } from '../services/mapVideos/update';
-import { deleteMapVideo } from '../services/mapVideos/delete';
-
-const getMapVideosSchema = createSelectSchema(mapVideosTable);
-
-const createMapVideoSchema = createInsertSchema(mapVideosTable);
-
-export const mapVideosController = new Elysia({ prefix: '/mapVideos' })
- .get('/', async () => await getAll(), {
- response: {
- 200: t.Array(getMapVideosSchema),
- 500: t.ObjectString({}),
- },
- })
- .use(authMiddleware)
- .post('/', async ({ body }) => await createMapVideo(body), {
- body: createMapVideoSchema,
- response: {
- 200: getMapVideosSchema,
- 500: t.ObjectString({}),
- },
- })
- .put(
- '/:id',
- async ({ body, params: { id } }) => await updateMapVideo(id, body),
- {
- params: t.Object({ id: t.String({ format: 'uuid' }) }),
- body: createMapVideoSchema,
- response: {
- 200: getMapVideosSchema,
- 404: t.ObjectString({}),
- 500: t.ObjectString({}),
- },
- }
- )
- .delete('/:id', async ({ params: { id } }) => await deleteMapVideo(id), {
- params: t.Object({ id: t.String({ format: 'uuid' }) }),
- response: {
- 200: getMapVideosSchema,
- 404: t.ObjectString({}),
- 500: t.ObjectString({}),
- },
- });
diff --git a/src/controllers/upload.ts b/src/controllers/upload.ts
index 29b8979..a4fd44c 100644
--- a/src/controllers/upload.ts
+++ b/src/controllers/upload.ts
@@ -1,6 +1,6 @@
import Elysia, { error, t } from 'elysia';
-import { authMiddleware } from '../middlewares/auth';
-import { s3client } from '../config/s3client';
+import { authMiddleware } from '../middlewares/auth.ts';
+import { s3client } from '../config/s3client.ts';
import { PutObjectCommand } from '@aws-sdk/client-s3';
import { randomUUIDv7 } from 'bun';
diff --git a/src/db/schema/index.ts b/src/db/schema/index.ts
index 81fbbc8..7b9e526 100644
--- a/src/db/schema/index.ts
+++ b/src/db/schema/index.ts
@@ -4,4 +4,5 @@ export * from './projects.ts';
export * from './tokens.ts';
export * from './companies.ts';
export * from './stories.ts';
-export * from './mapVideos.ts';
+export * from './map.ts';
+export * from './mail.ts';
diff --git a/src/db/schema/mail.ts b/src/db/schema/mail.ts
new file mode 100644
index 0000000..50cf3e7
--- /dev/null
+++ b/src/db/schema/mail.ts
@@ -0,0 +1,20 @@
+import { text } from 'drizzle-orm/pg-core';
+import { pgTable, uuid } from 'drizzle-orm/pg-core';
+
+export const mailTable = pgTable('mail', {
+ id: uuid('id').defaultRandom().primaryKey(),
+ fullname: text('fullname').notNull(),
+ email: text('email').notNull(),
+ phone: text('phone'),
+ request: text('request'),
+ products: text('products', {
+ enum: [
+ 'Интерактивная презентация',
+ 'Удаленная демонстрация',
+ 'Архитектурная визуализация',
+ 'Создание сайтов',
+ 'Web-тур по 360 сферам',
+ ],
+ }).array(),
+ from: text('from').notNull(),
+});
diff --git a/src/db/schema/map.ts b/src/db/schema/map.ts
new file mode 100644
index 0000000..e76ef9d
--- /dev/null
+++ b/src/db/schema/map.ts
@@ -0,0 +1,27 @@
+import { pgTable, text, uuid, varchar } from 'drizzle-orm/pg-core';
+import { companiesTable } from './companies';
+import { projectsTable } from './projects';
+import { relations } from 'drizzle-orm';
+
+export const mapTable = pgTable('map', {
+ id: uuid('id').defaultRandom().primaryKey(),
+ city: varchar('city', { length: 50 }).notNull(),
+ src: text('src'),
+ companyId: uuid('company_id')
+ .notNull()
+ .references(() => companiesTable.id),
+ projectId: uuid('project_id')
+ .notNull()
+ .references(() => projectsTable.id),
+});
+
+export const mapRelations = relations(mapTable, ({ one }) => ({
+ company: one(companiesTable, {
+ fields: [mapTable.companyId],
+ references: [companiesTable.id],
+ }),
+ project: one(projectsTable, {
+ fields: [mapTable.projectId],
+ references: [projectsTable.id],
+ }),
+}));
diff --git a/src/db/schema/mapVideos.ts b/src/db/schema/mapVideos.ts
deleted file mode 100644
index 6a8d22f..0000000
--- a/src/db/schema/mapVideos.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import { pgTable, text, uuid, varchar } from 'drizzle-orm/pg-core';
-import { companiesTable } from './companies';
-import { relations } from 'drizzle-orm';
-
-export const mapVideosTable = pgTable('map_videos', {
- id: uuid('id').defaultRandom().primaryKey(),
- city: varchar('city', { length: 50 }).notNull(),
- video: text('video').notNull(),
- companyId: uuid('company_id').references(() => companiesTable.id),
-});
-
-export const videosRelations = relations(mapVideosTable, ({ one }) => ({
- company: one(companiesTable, {
- fields: [mapVideosTable.companyId],
- references: [companiesTable.id],
- }),
-}));
diff --git a/src/index.ts b/src/index.ts
index 5d459d3..db9ba0b 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -10,10 +10,7 @@ import { companiesController } from './controllers/companies';
import { mailController } from './controllers/mail';
import { getReionNameController } from './controllers/getRegionName';
import { storiesController } from './controllers/stories';
-import { mapVideosController } from './controllers/mapVideos';
-import { db } from './db';
-import { projectsTable } from './db/schema';
-import { eq, ne } from 'drizzle-orm';
+import { mapController } from './controllers/map';
try {
const app = new Elysia();
@@ -30,7 +27,7 @@ try {
.use(uploadController)
.use(companiesController)
.use(storiesController)
- .use(mapVideosController)
+ .use(mapController)
.use(mailController)
.use(getReionNameController)
.listen(process.env.PORT);
diff --git a/src/middlewares/auth.ts b/src/middlewares/auth.ts
index 6210ccb..30cd278 100644
--- a/src/middlewares/auth.ts
+++ b/src/middlewares/auth.ts
@@ -5,16 +5,10 @@ import { verifyToken } from '../utils/verifyToken';
import { adminsTable } from '../db/schema';
export const authMiddleware = new Elysia()
- .derive({ as: 'scoped' }, async ({ headers, cookie, path }: Context) => {
- const token =
- (path === '/auth/refresh'
- ? cookie.refreshToken.value
- : cookie.accessToken.value) || headers.authorization;
+ .derive({ as: 'scoped' }, async ({ headers, path }: Context) => {
+ const token = headers['authorization'];
- const payload = await verifyToken(
- path === '/auth/refresh' ? 'refresh' : 'access',
- token
- );
+ const payload = await verifyToken('access', token);
if (!token || !payload)
return path === '/auth/check'
@@ -32,14 +26,9 @@ export const authMiddleware = new Elysia()
if (
!user ||
- user.tokens.every(
- ({ accessToken, refreshToken }) =>
- token !== (path === '/auth/refresh' ? refreshToken : accessToken)
- )
- ) {
- console.log("attempt to login with someone else's token");
+ user.tokens.every(({ accessToken }) => token !== accessToken)
+ )
return error(401, { error: 'Not authorized' });
- }
} catch (err) {
console.log((err as Error).message);
return error(500, {
diff --git a/src/services/articles/create.ts b/src/services/articles/create.ts
index d7c82c7..f9dd421 100644
--- a/src/services/articles/create.ts
+++ b/src/services/articles/create.ts
@@ -1,6 +1,6 @@
import { error } from 'elysia';
-import { db } from '../../db';
-import { articlesTable } from '../../db/schema';
+import { db } from '../../db/index.ts';
+import { articlesTable } from '../../db/schema/index.ts';
import { slugify } from 'transliteration';
export async function create(input: typeof articlesTable.$inferInsert) {
diff --git a/src/services/articles/getAll.ts b/src/services/articles/getAll.ts
index 40296d4..a20fe09 100644
--- a/src/services/articles/getAll.ts
+++ b/src/services/articles/getAll.ts
@@ -1,4 +1,4 @@
-import { and, arrayContains, not } from 'drizzle-orm';
+import { and, arrayContains, arrayOverlaps, desc, not } from 'drizzle-orm';
import { db } from '../../db';
import { articlesTable } from '../../db/schema';
import { error } from 'elysia';
@@ -10,8 +10,9 @@ export async function getAll(tags: string[] = [], offset = 0, limit = 10) {
limit,
where: and(
not(articlesTable.drafted),
- tags.length > 0 ? arrayContains(articlesTable.tags, tags) : undefined
+ tags.length > 0 ? arrayOverlaps(articlesTable.tags, tags) : undefined
),
+ orderBy: desc(articlesTable.createdAt),
});
} catch (err) {
console.log((err as Error).message);
diff --git a/src/services/articles/index.ts b/src/services/articles/index.ts
index ad09344..a9496a4 100644
--- a/src/services/articles/index.ts
+++ b/src/services/articles/index.ts
@@ -1,5 +1,5 @@
-export * from './getAll';
-export * from './getOne';
-export * from './create';
-export * from './remove';
-export * from './update';
+export * from './getAll.ts';
+export * from './getOne.ts';
+export * from './create.ts';
+export * from './remove.ts';
+export * from './update.ts';
diff --git a/src/services/articles/update.ts b/src/services/articles/update.ts
index 78cbbb8..3439aed 100644
--- a/src/services/articles/update.ts
+++ b/src/services/articles/update.ts
@@ -1,6 +1,6 @@
import { eq } from 'drizzle-orm';
-import { db } from '../../db';
-import { articlesTable } from '../../db/schema';
+import { db } from '../../db/index.ts';
+import { articlesTable } from '../../db/schema/index.ts';
import { error } from 'elysia';
import { slugify } from 'transliteration';
diff --git a/src/services/auth/generateTokens.ts b/src/services/auth/generateTokens.ts
index 90881ee..090484c 100644
--- a/src/services/auth/generateTokens.ts
+++ b/src/services/auth/generateTokens.ts
@@ -3,10 +3,13 @@ import { generateToken } from '../../utils/generateToken';
import { db } from '../../db';
import { tokensTable } from '../../db/schema';
-export async function generateTokens(
- adminId: string,
- cookie: Record>
-) {
+export async function generateTokens(adminId: string): Promise<
+ | {
+ accessToken: string;
+ refreshToken: string;
+ }
+ | ReturnType
+> {
const accessToken = await generateToken(adminId, 'access');
const refreshToken = await generateToken(adminId, 'refresh');
@@ -23,20 +26,6 @@ export async function generateTokens(
return error(500, { error: 'Something went wrong (Postgres insert)' });
}
- cookie.accessToken.set({
- value: accessToken,
- httpOnly: true,
- // secure: true,
- maxAge: 3600 * 24 * 30,
- });
-
- cookie.refreshToken.set({
- value: refreshToken,
- httpOnly: true,
- // secure: true,
- maxAge: 3600 * 24 * 30,
- });
-
return {
accessToken,
refreshToken,
diff --git a/src/services/auth/login.ts b/src/services/auth/login.ts
index 234188e..9ef0564 100644
--- a/src/services/auth/login.ts
+++ b/src/services/auth/login.ts
@@ -4,8 +4,8 @@ import { getUserByUsername } from '../admins/getByUsername';
import { generateTokens } from './generateTokens';
export async function login(
- body: { username: string; password: string },
- cookie: Record>
+ body: { username: string; password: string }
+ // cookie: Record>
) {
const { username, password } = body;
@@ -14,12 +14,28 @@ export async function login(
if (user instanceof ElysiaCustomStatusResponse)
return error(user.code, user.response.error);
- const passwordMatches = user
- ? Bun.password.verifySync(password, user.hashedPassword)
- : false;
-
- if (!user || !passwordMatches)
+ if (!user || !Bun.password.verifySync(password, user.hashedPassword))
return error(401, { error: 'Wrong credentials' });
- return await generateTokens(user.id, cookie);
+ const res = await generateTokens(user.id);
+
+ // if ('accessToken' in res && 'refreshToken' in res) {
+ // cookie.accessToken.set({
+ // value: res.accessToken,
+ // httpOnly: true,
+ // sameSite: 'lax',
+ // // secure: true,
+ // maxAge: 3600 * 24 * 30,
+ // });
+
+ // cookie.refreshToken.set({
+ // value: res.refreshToken,
+ // httpOnly: true,
+ // sameSite: 'lax',
+ // // secure: true,
+ // maxAge: 3600 * 24 * 30,
+ // });
+ // }
+
+ return res;
}
diff --git a/src/services/auth/logout.ts b/src/services/auth/logout.ts
index f18934d..c075a6a 100644
--- a/src/services/auth/logout.ts
+++ b/src/services/auth/logout.ts
@@ -4,11 +4,12 @@ import { tokensTable } from '../../db/schema';
import { and, eq } from 'drizzle-orm';
export async function logout(
- cookie: Record> & {
- accessToken: Cookie;
- refreshToken: Cookie;
- },
- adminId: string
+ adminId: string,
+ authorizatoin: string
+ // cookie: Record> & {
+ // accessToken: Cookie;
+ // refreshToken: Cookie;
+ // }
) {
try {
const result = await db
@@ -16,7 +17,7 @@ export async function logout(
.where(
and(
eq(tokensTable.adminId, adminId),
- eq(tokensTable.accessToken, cookie.accessToken.value!)
+ eq(tokensTable.accessToken, authorizatoin)
)
)
.returning();
@@ -29,8 +30,8 @@ export async function logout(
});
}
- cookie.accessToken.remove();
- cookie.refreshToken.remove();
+ // cookie.accessToken.remove();
+ // cookie.refreshToken.remove();
return {
success: true,
diff --git a/src/services/companies/index.ts b/src/services/companies/index.ts
index fcf3531..5e6e5e7 100644
--- a/src/services/companies/index.ts
+++ b/src/services/companies/index.ts
@@ -1,5 +1,5 @@
-export * from './getMany';
-export * from './getCount';
-export * from './create';
-export * from './update';
-export * from './remove';
+export * from './getMany.ts';
+export * from './getCount.ts';
+export * from './create.ts';
+export * from './update.ts';
+export * from './remove.ts';
diff --git a/src/services/map/createMapPoint.ts b/src/services/map/createMapPoint.ts
new file mode 100644
index 0000000..b36c070
--- /dev/null
+++ b/src/services/map/createMapPoint.ts
@@ -0,0 +1,14 @@
+import { error } from 'elysia';
+import { db } from '../../db';
+import { mapTable } from '../../db/schema';
+
+export async function createMapPoint(payload: typeof mapTable.$inferInsert) {
+ try {
+ const res = await db.insert(mapTable).values(payload).returning();
+ if (res.length) return res[0];
+ return error(500, 'Internal Server Error');
+ } catch (err) {
+ console.log((err as Error).message);
+ return error(500, 'Internal Server Error');
+ }
+}
diff --git a/src/services/mapVideos/delete.ts b/src/services/map/deleteMapPoint.ts
similarity index 55%
rename from src/services/mapVideos/delete.ts
rename to src/services/map/deleteMapPoint.ts
index 79aa005..03b8295 100644
--- a/src/services/mapVideos/delete.ts
+++ b/src/services/map/deleteMapPoint.ts
@@ -1,15 +1,15 @@
-import { eq } from 'drizzle-orm';
-import { db } from '../../db';
-import { mapVideosTable } from '../../db/schema';
import { error } from 'elysia';
+import { db } from '../../db';
+import { mapTable } from '../../db/schema';
+import { eq } from 'drizzle-orm';
-export async function deleteMapVideo(id: string) {
+export async function deleteMapPoint(id: string) {
try {
const res = await db
- .delete(mapVideosTable)
- .where(eq(mapVideosTable.id, id))
+ .delete(mapTable)
+ .where(eq(mapTable.id, id))
.returning();
- if (!res.length) return error(404, 'Not Found');
+ if (!res.length) return error(404, 'Map not found');
return res[0];
} catch (err) {
console.log((err as Error).message);
diff --git a/src/services/map/getByCity.ts b/src/services/map/getByCity.ts
new file mode 100644
index 0000000..0986be4
--- /dev/null
+++ b/src/services/map/getByCity.ts
@@ -0,0 +1,21 @@
+import { eq } from 'drizzle-orm';
+import { db } from '../../db';
+import { mapTable } from '../../db/schema';
+import { error } from 'elysia';
+
+export async function getByCity(city: string) {
+ try {
+ const res = await db.query.mapTable.findMany({
+ where: eq(mapTable.city, city),
+ with: {
+ company: true,
+ project: true,
+ },
+ });
+ if (!res) return error(404, { error: 'Map point not found' });
+ return res;
+ } catch (err) {
+ console.log((err as Error).message);
+ return error(500, 'Internal Server Error');
+ }
+}
diff --git a/src/services/map/updateMapPoint.ts b/src/services/map/updateMapPoint.ts
new file mode 100644
index 0000000..115064b
--- /dev/null
+++ b/src/services/map/updateMapPoint.ts
@@ -0,0 +1,22 @@
+import { error } from 'elysia';
+import { mapTable } from '../../db/schema';
+import { db } from '../../db';
+import { eq } from 'drizzle-orm';
+
+export async function updateMapPoint(
+ id: string,
+ payload: Partial
+) {
+ try {
+ const res = await db
+ .update(mapTable)
+ .set(payload)
+ .where(eq(mapTable.id, id))
+ .returning();
+ if (!res.length) return error(404, 'Map not found');
+ return res[0];
+ } catch (err) {
+ console.log((err as Error).message);
+ return error(500, 'Internal Server Error');
+ }
+}
diff --git a/src/services/mapVideos/create.ts b/src/services/mapVideos/create.ts
deleted file mode 100644
index 742f6dc..0000000
--- a/src/services/mapVideos/create.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { error } from 'elysia';
-import { db } from '../../db';
-import { mapVideosTable } from '../../db/schema';
-
-export async function createMapVideo(
- paylaod: typeof mapVideosTable.$inferInsert
-) {
- try {
- const res = await db.insert(mapVideosTable).values(paylaod).returning();
- if (!res) return error(500, 'Internal Server Error');
- return res[0];
- } catch (err) {
- console.log((err as Error).message);
- return error(500, 'Internal Server Error');
- }
-}
diff --git a/src/services/mapVideos/getAll.ts b/src/services/mapVideos/getAll.ts
deleted file mode 100644
index a04f3fa..0000000
--- a/src/services/mapVideos/getAll.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-import { error } from 'elysia';
-import { db } from '../../db';
-
-export async function getAll() {
- try {
- return await db.query.mapVideosTable.findMany({ with: { company: true } });
- } catch (err) {
- console.log((err as Error).message);
- return error(500, { error: 'Internal Server Error' });
- }
-}
diff --git a/src/services/mapVideos/update.ts b/src/services/mapVideos/update.ts
deleted file mode 100644
index 9230b68..0000000
--- a/src/services/mapVideos/update.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import { error } from 'elysia';
-import { db } from '../../db';
-import { mapVideosTable } from '../../db/schema';
-import { eq } from 'drizzle-orm';
-
-export async function updateMapVideo(
- id: string,
- payload: typeof mapVideosTable.$inferInsert
-) {
- try {
- const candidate = await db.query.mapVideosTable.findFirst();
- if (!candidate) return error(404, 'Not Found');
- const res = await db
- .update(mapVideosTable)
- .set(payload)
- .where(eq(mapVideosTable.id, id))
- .returning();
- if (!res) return error(500, 'Internal Server Error');
- return res[0];
- } catch (err) {
- console.log((err as Error).message);
- return error(500, 'Internal Server Error');
- }
-}
diff --git a/src/services/projects/getMany.ts b/src/services/projects/getMany.ts
index 4cce3d4..bd31649 100644
--- a/src/services/projects/getMany.ts
+++ b/src/services/projects/getMany.ts
@@ -1,4 +1,4 @@
-import { and, arrayContains, desc, eq } from 'drizzle-orm';
+import { and, arrayContains, arrayOverlaps, desc, eq } from 'drizzle-orm';
import { db } from '../../db';
import { projectsTable } from '../../db/schema';
import { error } from 'elysia';
@@ -12,7 +12,7 @@ export async function getMany(
try {
return await db.query.projectsTable.findMany({
where: and(
- tags.length > 0 ? arrayContains(projectsTable.tags, tags) : undefined,
+ tags.length > 0 ? arrayOverlaps(projectsTable.tags, tags) : undefined,
city ? eq(projectsTable.city, city) : undefined,
companyId ? eq(projectsTable.companyId, companyId) : undefined
),
diff --git a/tsconfig.json b/tsconfig.json
index 1dfa956..c0ac791 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -107,8 +107,7 @@
"./drizzle.config.ts",
"./env.d.ts",
"./src/**/*.ts",
- "./bun.config.ts"
- // "src/controllers/getRegionName.ts"
+ "./bun.build.ts"
],
"exclude": ["node_modules"]
}