Skip to content

Commit

Permalink
Merge pull request #1 from WodenWang820118/back-and-database
Browse files Browse the repository at this point in the history
feat: task backend endpoint
  • Loading branch information
WodenWang820118 authored May 25, 2024
2 parents ef99e59 + 9073042 commit 6995f71
Show file tree
Hide file tree
Showing 21 changed files with 1,326 additions and 192 deletions.
Binary file added database.sqlite
Binary file not shown.
18 changes: 18 additions & 0 deletions nest-backend/project.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,24 @@
"projectType": "application",
"tags": [],
"targets": {
"build": {
"executor": "@nx/webpack:webpack",
"outputs": ["{options.outputPath}"],
"defaultConfiguration": "production",
"options": {
"target": "node",
"compiler": "tsc",
"outputPath": "dist/nest-backend",
"main": "nest-backend/src/main.ts",
"tsConfig": "nest-backend/tsconfig.app.json",
"generatePackageJson": true,
"webpackConfig": "nest-backend/webpack.config.js"
},
"configurations": {
"development": {},
"production": {}
}
},
"serve": {
"executor": "@nx/js:node",
"defaultConfiguration": "development",
Expand Down
22 changes: 0 additions & 22 deletions nest-backend/src/app/app.controller.spec.ts

This file was deleted.

13 changes: 0 additions & 13 deletions nest-backend/src/app/app.controller.ts

This file was deleted.

16 changes: 9 additions & 7 deletions nest-backend/src/app/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { Module } from '@nestjs/common';

import { AppController } from './app.controller';
import { AppService } from './app.service';

import { ConfigModule } from '@nestjs/config';
import { dataBaseConfig } from '../app/database/database.config';
import { SequelizeModule } from '@nestjs/sequelize';
import { TaskModule } from './task/task.module';
@Module({
imports: [],
controllers: [AppController],
providers: [AppService],
imports: [
ConfigModule.forRoot(),
SequelizeModule.forRoot(dataBaseConfig),
TaskModule,
],
})
export class AppModule {}
21 changes: 0 additions & 21 deletions nest-backend/src/app/app.service.spec.ts

This file was deleted.

8 changes: 0 additions & 8 deletions nest-backend/src/app/app.service.ts

This file was deleted.

24 changes: 24 additions & 0 deletions nest-backend/src/app/database/database.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { SequelizeModuleOptions } from '@nestjs/sequelize';
import { join } from 'path';
import { cwd } from 'process';
import { SequelizeOptions } from 'sequelize-typescript';

function getDatabaseConfig(): Partial<
{
name?: string;
retryAttempts?: number;
retryDelay?: number;
autoLoadModels?: boolean;
synchronize?: boolean;
uri?: string;
} & Partial<SequelizeOptions>
> {
return {
dialect: 'sqlite',
storage: join(cwd(), 'database.sqlite'),
autoLoadModels: true,
synchronize: true,
};
}

export const dataBaseConfig: SequelizeModuleOptions = getDatabaseConfig();
8 changes: 8 additions & 0 deletions nest-backend/src/app/task/dto/create-task.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export class CreateTaskDto {
id: string;
text: string;
day: string;
reminder: boolean;
createdAt?: Date;
updatedAt?: Date;
}
4 changes: 4 additions & 0 deletions nest-backend/src/app/task/dto/update-task.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { PartialType } from '@nestjs/swagger';
import { CreateTaskDto } from './create-task.dto';

export class UpdateTaskDto extends PartialType(CreateTaskDto) {}
14 changes: 14 additions & 0 deletions nest-backend/src/app/task/entities/task.entity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { Column, Table, Model, PrimaryKey } from 'sequelize-typescript';

@Table({ tableName: 'Tasks' })
export class Task extends Model {
@PrimaryKey
@Column
id: string;
@Column
text: string;
@Column
day: string;
@Column
reminder: boolean;
}
41 changes: 41 additions & 0 deletions nest-backend/src/app/task/task.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import {
Body,
Controller,
Delete,
Get,
Param,
Post,
Put,
} from '@nestjs/common';
import { TaskService } from './task.service';
import { CreateTaskDto } from './dto/create-task.dto';

@Controller('tasks')
export class TaskController {
constructor(private taskService: TaskService) {}

@Get('')
async getTasks() {
return await this.taskService.findAll();
}

@Get(':id')
async getTask(id: string) {
return await this.taskService.findOne(id);
}

@Post('/create')
async createTask(@Body() task: CreateTaskDto) {
return await this.taskService.create(task);
}

@Put(':id')
async updateTask(@Body() task: CreateTaskDto) {
return await this.taskService.update(task.id, task);
}

@Delete(':id')
async deleteTask(@Param('id') id: string) {
return await this.taskService.remove(id);
}
}
13 changes: 13 additions & 0 deletions nest-backend/src/app/task/task.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { Module } from '@nestjs/common';
import { TaskService } from './task.service';
import { SequelizeModule } from '@nestjs/sequelize';
import { Task } from './entities/task.entity';
import { TaskController } from './task.controller';

@Module({
imports: [SequelizeModule.forFeature([Task])],
controllers: [TaskController],
providers: [TaskService],
exports: [SequelizeModule.forFeature([Task]), TaskService],
})
export class TaskModule {}
46 changes: 46 additions & 0 deletions nest-backend/src/app/task/task.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { Injectable } from '@nestjs/common';
import { CreateTaskDto } from './dto/create-task.dto';
import { UpdateTaskDto } from './dto/update-task.dto';
import { Task } from './entities/task.entity';
import { InjectModel } from '@nestjs/sequelize';

@Injectable()
export class TaskService {
constructor(
@InjectModel(Task)
private taskRepository: typeof Task
) {}

async create(createTaskDto: CreateTaskDto): Promise<Task> {
return await this.taskRepository.create(createTaskDto as any);
}

async findAll() {
return await this.taskRepository.findAll();
}

async findOne(id: string) {
return await this.taskRepository.findOne({ where: { id: id } });
}

async update(id: string, updateTaskDto: UpdateTaskDto) {
return await this.taskRepository.update(
{
text: updateTaskDto.text,
day: updateTaskDto.day,
reminder: updateTaskDto.reminder,
},
{ where: { id: id } }
);
}

async remove(id: string) {
return await this.taskRepository.destroy({ where: { id: id } });
}

async removeByName(name: string) {
return await this.taskRepository.destroy({
where: { title: name },
});
}
}
7 changes: 2 additions & 5 deletions nest-backend/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,10 @@ import { AppModule } from './app/app.module';

async function bootstrap() {
const app = await NestFactory.create(AppModule);
const globalPrefix = 'api';
app.setGlobalPrefix(globalPrefix);
app.enableCors();
const port = process.env.PORT || 3000;
await app.listen(port);
Logger.log(
`🚀 Application is running on: http://localhost:${port}/${globalPrefix}`
);
Logger.log(`🚀 Application is running on: http://localhost:${port}`);
}

bootstrap();
25 changes: 7 additions & 18 deletions nest-backend/webpack.config.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,8 @@
const { NxAppWebpackPlugin } = require('@nx/webpack/app-plugin');
const { join } = require('path');
const { composePlugins, withNx } = require('@nx/webpack');

module.exports = {
output: {
path: join(__dirname, '../dist/nest-backend'),
},
plugins: [
new NxAppWebpackPlugin({
target: 'node',
compiler: 'tsc',
main: './src/main.ts',
tsConfig: './tsconfig.app.json',
assets: ['./src/assets'],
optimization: false,
outputHashing: 'none',
}),
],
};
// Nx plugins for webpack.
module.exports = composePlugins(withNx(), (config) => {
// Update the webpack config as needed here.
// e.g. `config.plugins.push(new MyPlugin())`
return config;
});
2 changes: 1 addition & 1 deletion ng-tracker/src/app/interfaces/task.interface.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export interface Task {
id?: number;
id: string;
text: string;
day: string;
reminder: boolean;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { Task } from '../../../interfaces/task.interface';
import { FormBuilder, FormsModule, ReactiveFormsModule } from '@angular/forms';
import { Router } from '@angular/router';
import { TaskService } from '../../../shared/services/task.service';
import { v4 as uuidv4 } from 'uuid';

@Component({
selector: 'app-task-form',
Expand Down Expand Up @@ -102,6 +103,7 @@ export class TaskFormComponent {
}

const newTask = {
id: uuidv4(),
text: this.taskForm.value.text,
day: this.taskForm.value.day,
reminder: this.taskForm.value.reminder || false,
Expand Down
14 changes: 8 additions & 6 deletions ng-tracker/src/app/shared/services/task.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,13 @@ export class TaskService {
}

addTask(task: Task): Observable<Task> {
return this.http.post<Task>(this.apiUrl, task, httpOptions).pipe(
catchError((error) => {
console.log('Error: ', error);
return [];
})
);
return this.http
.post<Task>(`${this.apiUrl}/create`, task, httpOptions)
.pipe(
catchError((error) => {
console.log('Error: ', error);
return [];
})
);
}
}
Loading

0 comments on commit 6995f71

Please sign in to comment.