show first entry

This commit is contained in:
u80864958
2025-04-10 16:17:58 +02:00
commit fb2d784421
46 changed files with 15997 additions and 0 deletions

102
backend/auth/login.go Normal file
View File

@ -0,0 +1,102 @@
package auth
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
"time"
"git.schreifuchs.ch/schreifuchs/ng-blog/backend/model"
"github.com/golang-jwt/jwt/v5"
)
func Login(username, password string, secret []byte) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var login model.Login
if err := json.NewDecoder(r.Response.Request.Body).Decode(&login); err != nil {
w.WriteHeader(http.StatusUnauthorized)
return
}
if login.Name == username && login.Password == password {
token, err := createJWT(secret)
if err != nil {
w.WriteHeader(http.StatusUnauthorized)
return
}
err = json.NewEncoder(w).Encode(&model.LoginResponse{
Token: token,
})
if err != nil {
w.WriteHeader(http.StatusUnauthorized)
return
}
w.WriteHeader(http.StatusOK)
return
}
}
}
func Authenticated(secret []byte) func(http.HandlerFunc) http.Handler {
return func(next http.HandlerFunc) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Our middleware logic goes here...
token, err := extractToken(r)
if err != nil {
w.WriteHeader(http.StatusUnauthorized)
return
}
err = validateJWT(token, secret)
if err != nil {
w.WriteHeader(http.StatusUnauthorized)
return
}
next(w, r)
})
}
}
func createJWT(secret []byte) (token string, err error) {
return jwt.NewWithClaims(jwt.SigningMethodHS512, jwt.MapClaims{
"exp": time.Now().Add(time.Hour * 24).Unix(),
}).SignedString(secret)
}
func validateJWT(tokenString string, secret []byte) (err error) {
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (any, error) {
// Don't forget to validate the alg is what you expect:
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return secret, nil
})
if err != nil {
return
}
if date, err := token.Claims.GetExpirationTime(); err == nil && date.After(time.Now()) {
return nil
}
return errors.New("JWT not valid")
}
func extractToken(r *http.Request) (token string, err error) {
tokenHeader := r.Header.Get("Authorization") // Grab the token from the header
if tokenHeader == "" {
err = errors.New("missing token")
return
}
token = strings.TrimPrefix(tokenHeader, "Bearer ")
if token == "" {
err = errors.New("malformed token")
}
return
}

BIN
backend/blog.db Normal file

Binary file not shown.

View File

@ -0,0 +1,39 @@
package blog
import (
"encoding/json"
"fmt"
"net/http"
"git.schreifuchs.ch/schreifuchs/ng-blog/backend/model"
)
func (s Service) CreatePost(w http.ResponseWriter, r *http.Request) {
var post model.Post
if err := json.NewDecoder(r.Body).Decode(&post); err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, err.Error())
return
}
if err := s.db.Save(&post).Error; err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, err.Error())
}
json.NewEncoder(w).Encode(&post)
w.WriteHeader(http.StatusOK)
}
func (s Service) GetAllPosts(w http.ResponseWriter, r *http.Request) {
var posts []model.Post
if err := s.db.Preload("Comments").Order("created_at DESC").Find(&posts).Error; err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, err.Error())
return
}
json.NewEncoder(w).Encode(&posts)
w.WriteHeader(http.StatusOK)
}

11
backend/blog/resource.go Normal file
View File

@ -0,0 +1,11 @@
package blog
import "gorm.io/gorm"
type Service struct {
db *gorm.DB
}
func New(db *gorm.DB) *Service {
return &Service{db: db}
}

25
backend/cors/cors.go Normal file
View File

@ -0,0 +1,25 @@
package cors
import "net/http"
func HandlerForOrigin(origin string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if origin := r.Header.Get("Origin"); origin != "" {
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
w.Header().Set("Access-Control-Expose-Headers", "Authorization")
w.Header().Set("Access-Control-Allow-Credentials", "true")
}
if r.Method == "OPTIONS" {
return
}
next.ServeHTTP(w, r)
})
}
}
func DeafaultHandler(next http.Handler) http.Handler {
return HandlerForOrigin("*")(next)
}

18
backend/go.mod Normal file
View File

@ -0,0 +1,18 @@
module git.schreifuchs.ch/schreifuchs/ng-blog/backend
go 1.24.2
require (
github.com/golang-jwt/jwt/v5 v5.2.2
github.com/google/uuid v1.6.0
github.com/gorilla/mux v1.8.1
gorm.io/driver/sqlite v1.5.7
gorm.io/gorm v1.25.12
)
require (
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/mattn/go-sqlite3 v1.14.22 // indirect
golang.org/x/text v0.14.0 // indirect
)

18
backend/go.sum Normal file
View File

@ -0,0 +1,18 @@
github.com/golang-jwt/jwt/v5 v5.2.2 h1:Rl4B7itRWVtYIHFrSNd7vhTiz9UpLdi6gZhZ3wEeDy8=
github.com/golang-jwt/jwt/v5 v5.2.2/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
gorm.io/driver/sqlite v1.5.7 h1:8NvsrhP0ifM7LX9G4zPB97NwovUakUxc+2V2uuf3Z1I=
gorm.io/driver/sqlite v1.5.7/go.mod h1:U+J8craQU6Fzkcvu8oLeAQmi50TkwPEhHDEjQZXDah4=
gorm.io/gorm v1.25.12 h1:I0u8i2hWQItBq1WfE0o2+WuL9+8L21K9e2HHSTE/0f8=
gorm.io/gorm v1.25.12/go.mod h1:xh7N7RHfYlNc5EmcI/El95gXusucDrQnHXe0+CgWcLQ=

38
backend/main.go Normal file
View File

@ -0,0 +1,38 @@
package main
import (
"net/http"
"os"
"git.schreifuchs.ch/schreifuchs/ng-blog/backend/auth"
"git.schreifuchs.ch/schreifuchs/ng-blog/backend/blog"
"git.schreifuchs.ch/schreifuchs/ng-blog/backend/cors"
"git.schreifuchs.ch/schreifuchs/ng-blog/backend/model"
"github.com/gorilla/mux"
)
func main() {
user, ok := os.LookupEnv("USERNAME")
if !ok {
user = "admin"
}
password, ok := os.LookupEnv("PASSWORD")
if !ok {
password = "admin"
}
secret, ok := os.LookupEnv("SECRET")
if !ok {
secret = "Foo"
}
db := model.Init()
blg := blog.New(db)
r := mux.NewRouter()
r.Handle("/login", auth.Login(user, password, []byte(secret))).Methods("POST")
r.Handle("/posts", auth.Authenticated([]byte(secret))(blg.CreatePost)).Methods("POST")
r.Handle("/posts", http.HandlerFunc(blg.GetAllPosts)).Methods("GET")
r.Use(cors.HandlerForOrigin("*"))
http.ListenAndServe(":8080", r)
}

9
backend/model/auth.go Normal file
View File

@ -0,0 +1,9 @@
package model
type Login struct {
Name string `json:"name"`
Password string `json:"Password"`
}
type LoginResponse struct {
Token string `json:"token"`
}

19
backend/model/blog.go Normal file
View File

@ -0,0 +1,19 @@
package model
import (
"gorm.io/gorm"
)
type Post struct {
gorm.Model
ID uint `gorm:"primarykey" json:"id"`
Title string `json:"title"`
TLDR string `json:"tldr"`
Content string `json:"content"`
Comments []Comment
}
type Comment struct {
ID uint
PostID uint
Content string `json:"content"`
}

40
backend/model/init.go Normal file
View File

@ -0,0 +1,40 @@
package model
import (
"log"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
func Init() *gorm.DB {
db, err := gorm.Open(sqlite.Open("./blog.db"))
if err != nil {
log.Panic(err)
}
db.AutoMigrate(&Post{}, &Comment{})
db.Save(&Post{
ID: 1,
Title: "Foo",
TLDR: "Just some Foo Bar",
Content: "fkdj kjfk adjflkjdlö jdslj alsödj fla",
})
db.Save(&Post{
ID: 2,
Title: "Bar",
TLDR: "Just some Bar Baz",
Content: `
# Hello Worls
- alsödj
- adf adf
| adsf | asdf |
|------|------|
| adf | adsf |
`,
})
return db
}

17
frontend/.editorconfig Normal file
View File

@ -0,0 +1,17 @@
# Editor configuration, see https://editorconfig.org
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true
[*.ts]
quote_type = single
ij_typescript_use_double_quotes = false
[*.md]
max_line_length = off
trim_trailing_whitespace = false

42
frontend/.gitignore vendored Normal file
View File

@ -0,0 +1,42 @@
# See https://docs.github.com/get-started/getting-started-with-git/ignoring-files for more about ignoring files.
# Compiled output
/dist
/tmp
/out-tsc
/bazel-out
# Node
/node_modules
npm-debug.log
yarn-error.log
# IDEs and editors
.idea/
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# Visual Studio Code
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
.history/*
# Miscellaneous
/.angular/cache
.sass-cache/
/connect.lock
/coverage
/libpeerconnection.log
testem.log
/typings
# System files
.DS_Store
Thumbs.db

5
frontend/.postcssrc.json Normal file
View File

@ -0,0 +1,5 @@
{
"plugins": {
"@tailwindcss/postcss": {}
}
}

4
frontend/.vscode/extensions.json vendored Normal file
View File

@ -0,0 +1,4 @@
{
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=827846
"recommendations": ["angular.ng-template"]
}

20
frontend/.vscode/launch.json vendored Normal file
View File

@ -0,0 +1,20 @@
{
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "ng serve",
"type": "chrome",
"request": "launch",
"preLaunchTask": "npm: start",
"url": "http://localhost:4200/"
},
{
"name": "ng test",
"type": "chrome",
"request": "launch",
"preLaunchTask": "npm: test",
"url": "http://localhost:9876/debug.html"
}
]
}

42
frontend/.vscode/tasks.json vendored Normal file
View File

@ -0,0 +1,42 @@
{
// For more information, visit: https://go.microsoft.com/fwlink/?LinkId=733558
"version": "2.0.0",
"tasks": [
{
"type": "npm",
"script": "start",
"isBackground": true,
"problemMatcher": {
"owner": "typescript",
"pattern": "$tsc",
"background": {
"activeOnStart": true,
"beginsPattern": {
"regexp": "(.*?)"
},
"endsPattern": {
"regexp": "bundle generation complete"
}
}
}
},
{
"type": "npm",
"script": "test",
"isBackground": true,
"problemMatcher": {
"owner": "typescript",
"pattern": "$tsc",
"background": {
"activeOnStart": true,
"beginsPattern": {
"regexp": "(.*?)"
},
"endsPattern": {
"regexp": "bundle generation complete"
}
}
}
}
]
}

59
frontend/README.md Normal file
View File

@ -0,0 +1,59 @@
# Frontend
This project was generated using [Angular CLI](https://github.com/angular/angular-cli) version 19.2.6.
## Development server
To start a local development server, run:
```bash
ng serve
```
Once the server is running, open your browser and navigate to `http://localhost:4200/`. The application will automatically reload whenever you modify any of the source files.
## Code scaffolding
Angular CLI includes powerful code scaffolding tools. To generate a new component, run:
```bash
ng generate component component-name
```
For a complete list of available schematics (such as `components`, `directives`, or `pipes`), run:
```bash
ng generate --help
```
## Building
To build the project run:
```bash
ng build
```
This will compile your project and store the build artifacts in the `dist/` directory. By default, the production build optimizes your application for performance and speed.
## Running unit tests
To execute unit tests with the [Karma](https://karma-runner.github.io) test runner, use the following command:
```bash
ng test
```
## Running end-to-end tests
For end-to-end (e2e) testing, run:
```bash
ng e2e
```
Angular CLI does not come with an end-to-end testing framework by default. You can choose one that suits your needs.
## Additional Resources
For more information on using the Angular CLI, including detailed command references, visit the [Angular CLI Overview and Command Reference](https://angular.dev/tools/cli) page.

96
frontend/angular.json Normal file
View File

@ -0,0 +1,96 @@
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"frontend": {
"projectType": "application",
"schematics": {},
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:application",
"options": {
"outputPath": "dist/frontend",
"index": "src/index.html",
"browser": "src/main.ts",
"polyfills": [
"zone.js"
],
"tsConfig": "tsconfig.app.json",
"assets": [
{
"glob": "**/*",
"input": "public"
}
],
"styles": [
"src/styles.css"
],
"scripts": []
},
"configurations": {
"production": {
"budgets": [
{
"type": "initial",
"maximumWarning": "500kB",
"maximumError": "1MB"
},
{
"type": "anyComponentStyle",
"maximumWarning": "4kB",
"maximumError": "8kB"
}
],
"outputHashing": "all"
},
"development": {
"optimization": false,
"extractLicenses": false,
"sourceMap": true
}
},
"defaultConfiguration": "production"
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"configurations": {
"production": {
"buildTarget": "frontend:build:production"
},
"development": {
"buildTarget": "frontend:build:development"
}
},
"defaultConfiguration": "development"
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n"
},
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"polyfills": [
"zone.js",
"zone.js/testing"
],
"tsConfig": "tsconfig.spec.json",
"assets": [
{
"glob": "**/*",
"input": "public"
}
],
"styles": [
"src/styles.css"
],
"scripts": []
}
}
}
}
}
}

14925
frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

42
frontend/package.json Normal file
View File

@ -0,0 +1,42 @@
{
"name": "frontend",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "ng test"
},
"private": true,
"dependencies": {
"@angular/common": "^19.2.0",
"@angular/compiler": "^19.2.0",
"@angular/core": "^19.2.0",
"@angular/forms": "^19.2.0",
"@angular/platform-browser": "^19.2.0",
"@angular/platform-browser-dynamic": "^19.2.0",
"@angular/router": "^19.2.0",
"@tailwindcss/postcss": "^4.1.3",
"dompurify": "^3.2.5",
"marked": "^15.0.8",
"postcss": "^8.5.3",
"rxjs": "~7.8.0",
"tailwindcss": "^4.1.3",
"tslib": "^2.3.0",
"zone.js": "~0.15.0"
},
"devDependencies": {
"@angular-devkit/build-angular": "^19.2.6",
"@angular/cli": "^19.2.6",
"@angular/compiler-cli": "^19.2.0",
"@types/jasmine": "~5.1.0",
"jasmine-core": "~5.6.0",
"karma": "~6.4.0",
"karma-chrome-launcher": "~3.2.0",
"karma-coverage": "~2.2.0",
"karma-jasmine": "~5.1.0",
"karma-jasmine-html-reporter": "~2.1.0",
"typescript": "~5.7.2"
}
}

BIN
frontend/public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

View File

@ -0,0 +1,11 @@
<header
class="flex flex-row justify-between items-center px-5 bg-gray-300 h-16 w-full drop-shadow-xl/5"
>
<a routerLink="/">
<h1 class="text-2xl">My Blog</h1>
</a>
<nav></nav>
</header>
<main class="w-screen h-full px-5 sm:px-20 xl:px-96 pt-5">
<router-outlet />
</main>

View File

@ -0,0 +1,29 @@
import { TestBed } from '@angular/core/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [AppComponent],
}).compileComponents();
});
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
});
it(`should have the 'frontend' title`, () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app.title).toEqual('frontend');
});
it('should render title', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.nativeElement as HTMLElement;
expect(compiled.querySelector('h1')?.textContent).toContain('Hello, frontend');
});
});

View File

@ -0,0 +1,11 @@
import { Component } from '@angular/core';
import { RouterLink, RouterOutlet } from '@angular/router';
@Component({
selector: 'app-root',
imports: [RouterOutlet, RouterLink],
templateUrl: './app.component.html',
})
export class AppComponent {
title = 'frontend';
}

View File

@ -0,0 +1,13 @@
import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';
import { provideRouter, withComponentInputBinding } from '@angular/router';
import { routes } from './app.routes';
import { provideHttpClient } from '@angular/common/http';
export const appConfig: ApplicationConfig = {
providers: [
provideZoneChangeDetection({ eventCoalescing: true }),
provideRouter(routes, withComponentInputBinding()),
provideHttpClient(),
],
};

View File

@ -0,0 +1,8 @@
import { Routes } from '@angular/router';
import { HomeComponent } from './routes/home/home.component';
import { PostComponent } from './routes/post/post.component';
export const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'post', children: [{ path: ':id', component: PostComponent }] },
];

View File

@ -0,0 +1 @@
<div [innerHTML]="innerHTML"></div>

View File

@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MarkdownComponent } from './markdown.component';
describe('MarkdownComponent', () => {
let component: MarkdownComponent;
let fixture: ComponentFixture<MarkdownComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [MarkdownComponent]
})
.compileComponents();
fixture = TestBed.createComponent(MarkdownComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -0,0 +1,22 @@
import { Component, Input, OnChanges, OnInit } from '@angular/core';
import DOMPurify from 'dompurify';
import { marked } from 'marked';
@Component({
selector: 'app-markdown',
imports: [],
standalone: true,
templateUrl: './markdown.component.html',
})
export class MarkdownComponent implements OnChanges {
@Input() markdown: string = '';
innerHTML: string = '';
async parseMD() {
this.innerHTML = DOMPurify.sanitize(await marked.parse(this.markdown));
}
ngOnChanges(): void {
this.parseMD();
}
}

View File

@ -0,0 +1,11 @@
<p>Welcome to by little blog:</p>
<section class="grid gap-5 sm:grid-cols-2 2xl:grid-cols-3">
<button
*ngFor="let post of posts()"
class="p-5 flex flex-col items-start rounded-s bg-white drop-shadow-md hover:drop-shadow-xl"
[routerLink]="`/post/${post.id}`"
>
<h2 class="text-xl">{{ post.title }}</h2>
<p><strong>TL;DR; </strong>{{ post.tldr }}</p>
</button>
</section>

View File

@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { HomeComponent } from './home.component';
describe('HomeComponent', () => {
let component: HomeComponent;
let fixture: ComponentFixture<HomeComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [HomeComponent]
})
.compileComponents();
fixture = TestBed.createComponent(HomeComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -0,0 +1,19 @@
import { Component, inject, OnInit, Signal } from '@angular/core';
import { PostsService } from '../../shared/services/posts.service';
import { NgForOf } from '@angular/common';
import { RouterLink } from '@angular/router';
import { Post } from '../../shared/services/interfaces/post';
@Component({
selector: 'app-home',
imports: [NgForOf, RouterLink],
standalone: true,
templateUrl: './home.component.html',
})
export class HomeComponent {
private postsService = inject(PostsService);
get posts() {
return this.postsService.getPosts();
}
}

View File

@ -0,0 +1,7 @@
<h2 class="text-3xl">{{ post()?.title }}</h2>
<p class="mb-5 italic text-sm">TL;DR; {{ post()?.tldr }}</p>
<app-markdown
class="todo"
[markdown]="post()?.content || 'this post is empty'"
/>

View File

@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { PostComponent } from './post.component';
describe('PostComponent', () => {
let component: PostComponent;
let fixture: ComponentFixture<PostComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [PostComponent]
})
.compileComponents();
fixture = TestBed.createComponent(PostComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -0,0 +1,19 @@
import { Component, inject, Input } from '@angular/core';
import { PostsService } from '../../shared/services/posts.service';
import { JsonPipe, NgIf } from '@angular/common';
import { MarkdownComponent } from '../../components/markdown/markdown.component';
@Component({
selector: 'app-post',
imports: [MarkdownComponent],
standalone: true,
templateUrl: './post.component.html',
})
export class PostComponent {
private posts = inject(PostsService);
@Input() id!: string;
get post() {
return this.posts.getPost(parseInt(this.id));
}
}

View File

@ -0,0 +1,10 @@
export interface Post {
id: number;
title: string;
tldr: string;
content: string;
}
export interface Comment {
content: string;
}

View File

@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { PostsService } from './posts.service';
describe('PostsService', () => {
let service: PostsService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(PostsService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});

View File

@ -0,0 +1,40 @@
import { HttpClient } from '@angular/common/http';
import {
computed,
inject,
Injectable,
Signal,
signal,
WritableSignal,
} from '@angular/core';
import { Post } from './interfaces/post';
import { environment } from '../../../environments/environment';
@Injectable({
providedIn: 'root',
})
export class PostsService {
private http = inject(HttpClient);
private posts: WritableSignal<Map<number, Post>> = signal(new Map());
constructor() {
this.updatePosts(); // Pull posts immediately when the service is instantiated
}
updatePosts() {
this.http
.get<Post[]>(`${environment.apiRoot}/posts`)
.subscribe((res) => this.posts.set(new Map(res.map((p) => [p.id, p]))));
}
getPosts(): Signal<Post[]> {
return computed(() => Array.from(this.posts().values()));
}
getPost(id: number): Signal<Post | undefined> {
console.log(typeof id);
console.log(this.posts().has(id));
console.log(this.posts().has(2));
return computed(() => this.posts().get(id));
}
}

View File

@ -0,0 +1,4 @@
export const environment = {
production: false,
apiRoot: 'http://localhost:8080',
};

13
frontend/src/index.html Normal file
View File

@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Frontend</title>
<base href="/" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" type="image/x-icon" href="favicon.ico" />
</head>
<body>
<app-root></app-root>
</body>
</html>

7
frontend/src/main.ts Normal file
View File

@ -0,0 +1,7 @@
import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { AppComponent } from './app/app.component';
bootstrapApplication(AppComponent, appConfig).catch((err) =>
console.error(err),
);

59
frontend/src/styles.css Normal file
View File

@ -0,0 +1,59 @@
/* You can add global styles to this file, and also import other style files */
@import "tailwindcss";
/* apply todo css */
.todo {
@layer base {
body {
@apply bg-gray-50 text-gray-800 font-sans leading-relaxed text-base;
}
h1 {
@apply text-3xl font-bold text-gray-900 mt-8 mb-4;
}
h2 {
@apply text-2xl font-semibold text-gray-800 mt-6 mb-3;
}
h3 {
@apply text-xl font-semibold text-gray-700 mt-5 mb-2;
}
h4,
h5,
h6 {
@apply text-xl font-medium text-gray-600 mt-4 mb-2;
}
a {
@apply text-blue-600 hover:text-blue-800 transition-colors underline;
}
ul,
ol {
@apply pl-6 mb-4;
}
li {
@apply mb-1;
}
table {
@apply w-full border-collapse shadow-sm bg-white my-6;
}
th,
td {
@apply border border-gray-200 px-4 py-2 text-left;
}
th {
@apply bg-gray-100 font-semibold;
}
tr:nth-child(even) {
@apply bg-gray-50;
}
}
}

View File

@ -0,0 +1,15 @@
/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */
/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/app",
"types": []
},
"files": [
"src/main.ts"
],
"include": [
"src/**/*.d.ts"
]
}

27
frontend/tsconfig.json Normal file
View File

@ -0,0 +1,27 @@
/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */
/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */
{
"compileOnSave": false,
"compilerOptions": {
"outDir": "./dist/out-tsc",
"strict": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"skipLibCheck": true,
"isolatedModules": true,
"esModuleInterop": true,
"experimentalDecorators": true,
"moduleResolution": "bundler",
"importHelpers": true,
"target": "ES2022",
"module": "ES2022"
},
"angularCompilerOptions": {
"enableI18nLegacyMessageIdFormat": false,
"strictInjectionParameters": true,
"strictInputAccessModifiers": true,
"strictTemplates": true
}
}

View File

@ -0,0 +1,15 @@
/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */
/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/spec",
"types": [
"jasmine"
]
},
"include": [
"src/**/*.spec.ts",
"src/**/*.d.ts"
]
}