Removed old project, New project setup with Docker and Svelte

This commit is contained in:
Maximilian Giller 2024-10-08 15:37:07 +02:00
parent c0f8cc02d2
commit 36531dde2a
40 changed files with 274 additions and 415 deletions

23
.gitignore vendored
View file

@ -1,2 +1,21 @@
/.env node_modules
__pycache__/
# Output
.output
.vercel
/.svelte-kit
/build
# OS
.DS_Store
Thumbs.db
# Env
.env
.env.*
!.env.example
!.env.test
# Vite
vite.config.js.timestamp-*
vite.config.ts.timestamp-*

1
.npmrc Normal file
View file

@ -0,0 +1 @@
engine-strict=true

4
.prettierignore Normal file
View file

@ -0,0 +1,4 @@
# Package Managers
package-lock.json
pnpm-lock.yaml
yarn.lock

8
.prettierrc Normal file
View file

@ -0,0 +1,8 @@
{
"useTabs": true,
"singleQuote": true,
"trailingComma": "none",
"printWidth": 100,
"plugins": ["prettier-plugin-svelte"],
"overrides": [{ "files": "*.svelte", "options": { "parser": "svelte" } }]
}

View file

@ -1,3 +1,38 @@
# Zauberkiste # create-svelte
A selfhosted wishlist manager. Everything you need to build a Svelte project, powered by [`create-svelte`](https://github.com/sveltejs/kit/tree/main/packages/create-svelte).
## Creating a project
If you're seeing this, you've probably already done this step. Congrats!
```bash
# create a new project in the current directory
npm create svelte@latest
# create a new project in my-app
npm create svelte@latest my-app
```
## Developing
Once you've created a project and installed dependencies with `npm install` (or `pnpm install` or `yarn`), start a development server:
```bash
npm run dev
# or start the server and open the app in a new browser tab
npm run dev -- --open
```
## Building
To create a production version of your app:
```bash
npm run build
```
You can preview the production build with `npm run preview`.
> To deploy your app, you may need to install an [adapter](https://kit.svelte.dev/docs/adapters) for your target environment.

17
docker-compose.yml Normal file
View file

@ -0,0 +1,17 @@
version: '3'
services:
zauberkiste:
build:
context: .
target: dev # Build the development target
ports:
- "5173:5173"
- "24678:24678"
volumes:
- .:/app
- /app/node_modules
- ./data:/app/data
container_name: svelte-app-dev
environment:
NODE_ENV: development

51
dockerfile Normal file
View file

@ -0,0 +1,51 @@
# Stage 1: Base stage
FROM node:18 AS base
# Set the working directory
WORKDIR /app
# Copy package.json and package-lock.json
COPY package*.json ./
# Install dependencies
RUN npm install
# Copy the rest of the application files
COPY . .
# Define build arguments
ARG NODE_ENV
ENV NODE_ENV=$NODE_ENV
# Stage 2: Development stage
FROM base AS dev
# Expose ports needed for the development server and hot module reloading
EXPOSE 5173 24678
# In development mode, run the dev server
CMD ["npm", "run", "dev", "--", "--host"]
# Stage 3: Build for production
FROM base AS build
# Build the Svelte app in production mode
RUN npm run build
# Stage 4: Production stage
FROM node:18-alpine AS prod
# Install a lightweight server to serve the production build
RUN npm install -g serve
# Set the working directory
WORKDIR /app
# Copy the built files from the build stage
COPY --from=build /app/build /app/build
# Expose port 5000 for serving the production app
EXPOSE 5000
# Serve the production build
CMD ["serve", "-s", "build", "-l", "5000"]

32
eslint.config.js Normal file
View file

@ -0,0 +1,32 @@
import eslint from '@eslint/js';
import prettier from 'eslint-config-prettier';
import svelte from 'eslint-plugin-svelte';
import globals from 'globals';
import tseslint from 'typescript-eslint';
export default tseslint.config(
eslint.configs.recommended,
...tseslint.configs.recommended,
...svelte.configs['flat/recommended'],
prettier,
...svelte.configs['flat/prettier'],
{
languageOptions: {
globals: {
...globals.browser,
...globals.node
}
}
},
{
files: ['**/*.svelte'],
languageOptions: {
parserOptions: {
parser: tseslint.parser
}
}
},
{
ignores: ['build/', '.svelte-kit/', 'dist/']
}
);

32
package.json Normal file
View file

@ -0,0 +1,32 @@
{
"name": "zauberkiste",
"version": "0.0.1",
"private": true,
"scripts": {
"dev": "vite dev",
"build": "vite build",
"preview": "vite preview",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
"lint": "prettier --check . && eslint .",
"format": "prettier --write ."
},
"devDependencies": {
"@sveltejs/adapter-auto": "^3.0.0",
"@sveltejs/kit": "^2.0.0",
"@sveltejs/vite-plugin-svelte": "^3.0.0",
"@types/eslint": "^9.6.0",
"eslint": "^9.0.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-svelte": "^2.36.0",
"globals": "^15.0.0",
"prettier": "^3.1.1",
"prettier-plugin-svelte": "^3.1.2",
"svelte": "^4.2.7",
"svelte-check": "^4.0.0",
"typescript": "^5.0.0",
"typescript-eslint": "^8.0.0",
"vite": "^5.0.3"
},
"type": "module"
}

View file

@ -1,2 +0,0 @@
Django>=4.2.7
mysqlclient

13
src/app.d.ts vendored Normal file
View file

@ -0,0 +1,13 @@
// See https://kit.svelte.dev/docs/types#app
// for information about these interfaces
declare global {
namespace App {
// interface Error {}
// interface Locals {}
// interface PageData {}
// interface PageState {}
// interface Platform {}
}
}
export {};

12
src/app.html Normal file
View file

@ -0,0 +1,12 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
%sveltekit.head%
</head>
<body data-sveltekit-preload-data="hover">
<div style="display: contents">%sveltekit.body%</div>
</body>
</html>

Binary file not shown.

1
src/lib/index.ts Normal file
View file

@ -0,0 +1 @@
// place files you want to import through the `$lib` alias in this folder.

View file

@ -1,22 +0,0 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'zauberkiste.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()

2
src/routes/+page.svelte Normal file
View file

@ -0,0 +1,2 @@
<h1>Welcome to SvelteKit</h1>
<p>Visit <a href="https://kit.svelte.dev">kit.svelte.dev</a> to read the documentation</p>

View file

@ -1,3 +0,0 @@
from django.contrib import admin
# Register your models here.

View file

@ -1,6 +0,0 @@
from django.apps import AppConfig
class WishlistsConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'wishlists'

View file

@ -1,16 +0,0 @@
from uuid import UUID
from django.http import Http404
from wishlists.models import Wishlist
def get_wishlist_by_uuid(uuid: UUID) -> Wishlist:
return Wishlist.objects.get(id=uuid)
def get_wishlist_or_404_by_uuid(uuid: UUID) -> Wishlist:
try:
return get_wishlist_by_uuid(uuid)
except Wishlist.DoesNotExist:
raise Http404("This wishlist does not exist.")

View file

@ -1,40 +0,0 @@
# Generated by Django 4.2.7 on 2023-11-27 22:52
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Wishlist',
fields=[
('id', models.UUIDField(primary_key=True, serialize=False)),
('name', models.CharField(max_length=200)),
('description', models.CharField(max_length=2000)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
],
),
migrations.CreateModel(
name='WishlistItem',
fields=[
('id', models.UUIDField(primary_key=True, serialize=False)),
('name', models.CharField(max_length=200)),
('description', models.CharField(max_length=2000)),
('url', models.CharField(max_length=2000)),
('price', models.FloatField()),
('image', models.CharField(blank=True, max_length=2000, null=True)),
('gifted', models.BooleanField(default=False)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('wishlist', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='wishlists.wishlist')),
],
),
]

View file

@ -1,33 +0,0 @@
# Generated by Django 4.2.7 on 2023-11-27 23:02
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('wishlists', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='wishlist',
name='description',
field=models.CharField(max_length=2000, null=True),
),
migrations.AlterField(
model_name='wishlistitem',
name='description',
field=models.CharField(max_length=2000, null=True),
),
migrations.AlterField(
model_name='wishlistitem',
name='price',
field=models.FloatField(null=True),
),
migrations.AlterField(
model_name='wishlistitem',
name='url',
field=models.CharField(max_length=2000, null=True),
),
]

View file

@ -1,30 +0,0 @@
from django.db import models
class Wishlist(models.Model):
id = models.UUIDField(primary_key=True)
name = models.CharField(max_length=200)
description = models.CharField(max_length=2000, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return f"{self.name} ({self.id})"
class WishlistItem(models.Model):
id = models.UUIDField(primary_key=True)
wishlist = models.ForeignKey(Wishlist, on_delete=models.CASCADE)
name = models.CharField(max_length=200)
description = models.CharField(max_length=2000, null=True)
order = models.IntegerField(null=True)
url = models.CharField(max_length=2000, null=True)
price = models.FloatField(null=True)
image = models.CharField(max_length=2000, blank=True, null=True)
gifted = models.BooleanField(default=False)
reveal_date = models.DateTimeField(null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return f"{self.name} ({self.id})"

View file

@ -1,9 +0,0 @@
{% if wishlist %}
<h1>{{ wishlist.name }}</h1>
<sub>Created on {{ wishlist.created_at }}</sub>
{% if wishlist.description %}
<p>{{ wishlist.description }}</p>
{% endif %}
{% else %}
<p>Wishlist not found.</p>
{% endif %}

View file

@ -1,37 +0,0 @@
{% if wishlist %}
<h1>{{ wishlist.name }}</h1>
<sub>Created on {{ wishlist.created_at }}</sub>
{% if wishlist.description %}
<p>{{ wishlist.description }}</p>
{% endif %}
<a href="{% url 'public' wishlist.id %}">Public link</a>
<table>
<thead>
<tr>
<th>Item</th>
<th>Price</th>
<th>Link</th>
<th>Priority</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for item in wishlist_items %}
<tr>
<td>{{ item.name }}</td>
<td>{{ item.price }}</td>
<td><a href="{{ item.link }}">{{ item.link }}</a></td>
<td>{{ item.priority }}</td>
<td>
<a href="/items/{{ item.id }}/edit">Edit</a>
<a href="/items/{{ item.id }}/delete">Delete</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p>Wishlist not found.</p>
{% endif %}

View file

@ -1,3 +0,0 @@
from django.test import TestCase
# Create your tests here.

View file

@ -1,9 +0,0 @@
from django.urls import path
from . import views
urlpatterns = [
path("public/<uuid:wishlist_id>/", views.public, name="public"),
path("owner/<uuid:wishlist_id>/", views.owner, name="owner"),
path("", views.index, name="index"),
]

View file

@ -1,27 +0,0 @@
from uuid import UUID
from django.http import HttpResponse, Http404
from django.template import loader
from .handler.wishlist.get_wishlist_handler import get_wishlist_or_404_by_uuid
from .models import Wishlist
# Create your views here.
def index(request):
return HttpResponse("Hello, world. You're at the wishlists index.")
def owner(request, wishlist_id: UUID):
wishlist = get_wishlist_or_404_by_uuid(wishlist_id)
return HttpResponse(f"You are the owner of wishlist '{wishlist.name}'.")
def public(request, wishlist_id: UUID):
template = loader.get_template("public/index.html")
wishlist = get_wishlist_or_404_by_uuid(wishlist_id)
context = {
"wishlist": wishlist,
"wishlist_items": wishlist.wishlistitem_set.all(),
}
return HttpResponse(template.render(context, request))

View file

@ -1,16 +0,0 @@
"""
ASGI config for zauberkiste project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'zauberkiste.settings')
application = get_asgi_application()

View file

@ -1,123 +0,0 @@
"""
Django settings for zauberkiste project.
Generated by 'django-admin startproject' using Django 4.2.7.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.2/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "django-insecure-jrs0@9gnu_))f6(%25n30yze^d93#62%l+*8yw+6b^j3_#po9c"
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
"wishlists.apps.WishlistsConfig",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
]
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]
ROOT_URLCONF = "zauberkiste.urls"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]
WSGI_APPLICATION = "zauberkiste.wsgi.application"
# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "db.sqlite3",
}
}
# Password validation
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
},
{
"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
},
{
"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
},
{
"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.2/topics/i18n/
LANGUAGE_CODE = "en-us"
TIME_ZONE = "Europe/Berlin"
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/
STATIC_URL = "static/"
# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

View file

@ -1,19 +0,0 @@
"""
URL configuration for zauberkiste project.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.urls import path, include
urlpatterns = [path("", include("wishlists.urls"))]

View file

@ -1,16 +0,0 @@
"""
WSGI config for zauberkiste project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'zauberkiste.settings')
application = get_wsgi_application()

BIN
static/favicon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

18
svelte.config.js Normal file
View file

@ -0,0 +1,18 @@
import adapter from '@sveltejs/adapter-auto';
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
/** @type {import('@sveltejs/kit').Config} */
const config = {
// Consult https://kit.svelte.dev/docs/integrations#preprocessors
// for more information about preprocessors
preprocess: vitePreprocess(),
kit: {
// adapter-auto only supports some environments, see https://kit.svelte.dev/docs/adapter-auto for a list.
// If your environment is not supported, or you settled on a specific environment, switch out the adapter.
// See https://kit.svelte.dev/docs/adapters for more information about adapters.
adapter: adapter()
}
};
export default config;

19
tsconfig.json Normal file
View file

@ -0,0 +1,19 @@
{
"extends": "./.svelte-kit/tsconfig.json",
"compilerOptions": {
"allowJs": true,
"checkJs": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"sourceMap": true,
"strict": true,
"moduleResolution": "bundler"
}
// Path aliases are handled by https://kit.svelte.dev/docs/configuration#alias
// except $lib which is handled by https://kit.svelte.dev/docs/configuration#files
//
// If you want to overwrite includes/excludes, make sure to copy over the relevant includes/excludes
// from the referenced tsconfig.json - TypeScript does not merge them in
}

6
vite.config.ts Normal file
View file

@ -0,0 +1,6 @@
import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vite';
export default defineConfig({
plugins: [sveltekit()]
});