Compare commits
2 Commits
master
...
5ac529ce26
Author | SHA1 | Date | |
---|---|---|---|
5ac529ce26
|
|||
fa5d1e2689
|
20
api/api.go
20
api/api.go
@@ -5,8 +5,6 @@ import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"git.dubyatp.xyz/chat-api-server/db"
|
||||
"github.com/go-chi/chi/v5"
|
||||
@@ -38,7 +36,7 @@ func Start() {
|
||||
r := chi.NewRouter()
|
||||
|
||||
r.Use(cors.Handler(cors.Options{
|
||||
AllowedOrigins: strings.Split(os.Getenv("ALLOWED_ORIGINS"), ","),
|
||||
AllowedOrigins: []string{"http://localhost:5000"},
|
||||
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
|
||||
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
|
||||
ExposedHeaders: []string{"Link"},
|
||||
@@ -70,22 +68,6 @@ func Start() {
|
||||
r.Get("/", Whoami)
|
||||
})
|
||||
|
||||
r.Route("/channels", func(r chi.Router) {
|
||||
r.Use(SessionAuthMiddleware)
|
||||
|
||||
r.Get("/", ListChannels)
|
||||
r.Route("/{channelID}", func(r chi.Router) {
|
||||
r.Use(ChannelCtx) // Load channel
|
||||
r.Get("/", GetChannel)
|
||||
r.Delete("/", DeleteChannel)
|
||||
r.Post("/edit", EditChannel)
|
||||
})
|
||||
r.Route("/new", func(r chi.Router) {
|
||||
r.Use(LoginCtx)
|
||||
r.Post("/", NewChannel)
|
||||
})
|
||||
})
|
||||
|
||||
r.Route("/messages", func(r chi.Router) {
|
||||
r.Use(SessionAuthMiddleware) // Protect with authentication
|
||||
|
||||
|
215
api/channel.go
215
api/channel.go
@@ -1,215 +0,0 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/go-chi/render"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func ChannelCtx(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
slog.Debug("channel: entering ChannelCtx middleware")
|
||||
var channel *Channel
|
||||
var err error
|
||||
|
||||
if channelID := chi.URLParam(r, "channelID"); channelID != "" {
|
||||
slog.Debug("channel: fetching channel", "channelID", channelID)
|
||||
channel, err = dbGetChannel(channelID)
|
||||
} else {
|
||||
slog.Error("channel: channelID not found in URL parameters")
|
||||
render.Render(w, r, ErrNotFound)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
slog.Error("channel: failed to fetch channel", "channelID", chi.URLParam(r, "channelID"), "error", err)
|
||||
render.Render(w, r, ErrNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
slog.Debug("channel: successfully fetched channel", "channelID", channel.ID)
|
||||
ctx := context.WithValue(r.Context(), channelKey{}, channel)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
func GetChannel(w http.ResponseWriter, r *http.Request) {
|
||||
slog.Debug("channel: entering GetChannel handler")
|
||||
channel, ok := r.Context().Value(channelKey{}).(*Channel)
|
||||
if !ok || channel == nil {
|
||||
slog.Error("channel: channel not found in context")
|
||||
render.Render(w, r, ErrNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
slog.Debug("channel: rendering channel", "channelID", channel.ID)
|
||||
if err := render.Render(w, r, NewChannelResponse(channel)); err != nil {
|
||||
slog.Error("channel: failed to render channel response", "channelID", channel.ID, "error", err)
|
||||
render.Render(w, r, ErrRender(err))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func ListChannels(w http.ResponseWriter, r *http.Request) {
|
||||
slog.Debug("channel: entering ListChannels handler")
|
||||
dbChannels, err := dbGetAllChannels()
|
||||
if err != nil {
|
||||
slog.Error("channel: failed to fetch channels", "error", err)
|
||||
render.Render(w, r, ErrRender(err))
|
||||
return
|
||||
}
|
||||
|
||||
slog.Debug("channel: successfully fetched channels", "count", len(dbChannels))
|
||||
if err := render.RenderList(w, r, NewChannelListResponse(dbChannels)); err != nil {
|
||||
slog.Error("channel: failed to render channel list response", "error", err)
|
||||
render.Render(w, r, ErrRender(err))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func EditChannel(w http.ResponseWriter, r *http.Request) {
|
||||
slog.Debug("channel: entering EditChannel handler")
|
||||
channel, ok := r.Context().Value(channelKey{}).(*Channel)
|
||||
if !ok || channel == nil {
|
||||
slog.Error("channel: channel not found in context")
|
||||
render.Render(w, r, ErrNotFound)
|
||||
return
|
||||
}
|
||||
err := r.ParseMultipartForm(64 << 10)
|
||||
if err != nil {
|
||||
slog.Error("channel: failed to parse multipart form", "error", err)
|
||||
http.Error(w, "Unable to parse form", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
channelName := r.FormValue("name")
|
||||
channeltype := r.FormValue("type")
|
||||
if channelName == "" || channeltype == "" {
|
||||
slog.Error("channel: channel name or type is empty")
|
||||
http.Error(w, "Channel name or type cannot be empty", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
slog.Debug("channel: updating channel", "channelID", channel.ID)
|
||||
|
||||
channel.Name = channelName
|
||||
channel.Type = channeltype
|
||||
|
||||
err = dbUpdateChannel(channel)
|
||||
if err != nil {
|
||||
slog.Error("channel: failed to update channel", "channelID", channel.ID, "error", err)
|
||||
render.Render(w, r, ErrRender(err))
|
||||
return
|
||||
}
|
||||
|
||||
slog.Debug("channel: successfully updated channel", "channelID", channel.ID)
|
||||
if err := render.Render(w, r, NewChannelResponse(channel)); err != nil {
|
||||
slog.Error("channel: failed to render updated channel response", "channelID", channel.ID, "error", err)
|
||||
render.Render(w, r, ErrRender(err))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func DeleteChannel(w http.ResponseWriter, r *http.Request) {
|
||||
slog.Debug("channel: entering DeleteChannel handler")
|
||||
channel, ok := r.Context().Value(channelKey{}).(*Channel)
|
||||
if !ok || channel == nil {
|
||||
slog.Error("channel: channel not found in context")
|
||||
render.Render(w, r, ErrNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
slog.Debug("channel: deleting channel", "channelID", channel.ID)
|
||||
err := dbDeleteChannel(channel.ID.String())
|
||||
if err != nil {
|
||||
slog.Error("channel: failed to delete channel", "channelID", channel.ID, "error", err)
|
||||
render.Render(w, r, ErrRender(err))
|
||||
return
|
||||
}
|
||||
|
||||
slog.Debug("channel: successfully deleted channel", "channelID", channel.ID)
|
||||
if err := render.Render(w, r, NewChannelResponse(channel)); err != nil {
|
||||
slog.Error("channel: failed to render deleted channel response", "channelID", channel.ID, "error", err)
|
||||
render.Render(w, r, ErrRender(err))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func newChannelID() uuid.UUID {
|
||||
return uuid.New()
|
||||
}
|
||||
|
||||
func NewChannel(w http.ResponseWriter, r *http.Request) {
|
||||
slog.Debug("channel: entering NewChannel handler")
|
||||
err := r.ParseMultipartForm(64 << 10)
|
||||
if err != nil {
|
||||
slog.Error("channel: failed to parse multipart form", "error", err)
|
||||
http.Error(w, "Unable to parse form", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
channelName := r.FormValue("name")
|
||||
channeltype := r.FormValue("type")
|
||||
if channelName == "" || channeltype == "" {
|
||||
slog.Error("channel: channel name or type is empty")
|
||||
http.Error(w, "Channel name or type cannot be empty", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
channel := Channel{
|
||||
ID: newChannelID(),
|
||||
Name: channelName,
|
||||
Type: channeltype,
|
||||
Created: time.Now(),
|
||||
}
|
||||
|
||||
slog.Debug("channel: creating new channel", "channelID", channel.ID)
|
||||
err = dbAddChannel(&channel)
|
||||
if err != nil {
|
||||
slog.Error("channel: failed to add new channel", "channelID", channel.ID, "error", err)
|
||||
render.Render(w, r, ErrRender(err))
|
||||
return
|
||||
}
|
||||
|
||||
slog.Debug("channel: successfulyl created new channel", "channelID", channel.ID)
|
||||
render.Render(w, r, NewChannelResponse(&channel))
|
||||
}
|
||||
|
||||
type channelKey struct{}
|
||||
|
||||
type Channel struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Created time.Time `json:"created"`
|
||||
}
|
||||
|
||||
type ChannelRequest struct {
|
||||
*Channel
|
||||
}
|
||||
|
||||
type ChannelResponse struct {
|
||||
*Channel
|
||||
}
|
||||
|
||||
func (c ChannelResponse) MarshalJson() ([]byte, error) {
|
||||
type OrderedChannelResponse struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Created string `json:"created"`
|
||||
}
|
||||
|
||||
ordered := OrderedChannelResponse{
|
||||
ID: c.Channel.ID,
|
||||
Name: c.Channel.Name,
|
||||
Type: c.Channel.Type,
|
||||
Created: c.Channel.Created.Format(time.RFC3339),
|
||||
}
|
||||
return json.Marshal(ordered)
|
||||
}
|
99
api/db.go
99
api/db.go
@@ -239,102 +239,3 @@ func dbDeleteMessage(id string) error {
|
||||
slog.Debug("db: message deleted", "messageid", id)
|
||||
return nil
|
||||
}
|
||||
|
||||
func dbAddChannel(channel *Channel) error {
|
||||
query := `INSERT INTO channels (id, name, type, created) VALUES (?, ?, ?, ?)`
|
||||
err := db.Session.Query(query,
|
||||
channel.ID,
|
||||
channel.Name,
|
||||
channel.Type,
|
||||
channel.Created).Exec()
|
||||
if err != nil {
|
||||
slog.Error("db: failed to add channel", "error", err, "channelid", channel.ID)
|
||||
return fmt.Errorf("failed to add channel")
|
||||
}
|
||||
|
||||
slog.Debug("db: channel added", "channelid", channel.ID)
|
||||
return nil
|
||||
}
|
||||
|
||||
func dbGetChannel(id string) (*Channel, error) {
|
||||
query := `SELECT id, name, type, created FROM channels WHERE id = ?`
|
||||
var channel Channel
|
||||
err := db.Session.Query(query, id).Scan(
|
||||
&channel.ID,
|
||||
&channel.Name,
|
||||
&channel.Type,
|
||||
&channel.Created)
|
||||
if err == gocql.ErrNotFound {
|
||||
slog.Debug("db: channel not found", "channelid", id)
|
||||
return nil, errors.New("Channel not found")
|
||||
} else if err != nil {
|
||||
slog.Error("db: failed to query channel", "error", err)
|
||||
return nil, fmt.Errorf("failed to query channel")
|
||||
}
|
||||
|
||||
slog.Debug("db: channel found", "channelid", channel.ID)
|
||||
return &channel, nil
|
||||
}
|
||||
|
||||
func dbGetAllChannels() ([]*Channel, error) {
|
||||
query := `SELECT id, name, type, created FROM channels`
|
||||
iter := db.Session.Query(query).Iter()
|
||||
defer iter.Close()
|
||||
|
||||
var channels []*Channel
|
||||
for {
|
||||
channel := &Channel{}
|
||||
if !iter.Scan(
|
||||
&channel.ID,
|
||||
&channel.Name,
|
||||
&channel.Type,
|
||||
&channel.Created) {
|
||||
break
|
||||
}
|
||||
channels = append(channels, channel)
|
||||
}
|
||||
|
||||
if err := iter.Close(); err != nil {
|
||||
slog.Error("db: failed to iterate channels", "error", err)
|
||||
return nil, fmt.Errorf("failed to iterate channels")
|
||||
}
|
||||
|
||||
if len(channels) == 0 {
|
||||
slog.Debug("db: no channels found")
|
||||
return nil, errors.New("no channels found")
|
||||
}
|
||||
|
||||
slog.Debug("db: channel list returned")
|
||||
return channels, nil
|
||||
}
|
||||
|
||||
func dbUpdateChannel(updatedChannel *Channel) error {
|
||||
query := `UPDATE channels SET name = ?, type = ?, created = ? WHERE id = ?`
|
||||
|
||||
err := db.Session.Query(query,
|
||||
updatedChannel.Name,
|
||||
updatedChannel.Type,
|
||||
updatedChannel.Created,
|
||||
updatedChannel.ID).Exec()
|
||||
|
||||
if err != nil {
|
||||
slog.Error("db: failed to update channel", "error", err, "channelid", updatedChannel.ID)
|
||||
return fmt.Errorf("failed to update channel")
|
||||
}
|
||||
|
||||
slog.Debug("db: channel updated", "channelid", updatedChannel.ID)
|
||||
return nil
|
||||
}
|
||||
|
||||
func dbDeleteChannel(id string) error {
|
||||
query := `DELETE FROM channels WHERE id = ?`
|
||||
|
||||
err := db.Session.Query(query, id).Exec()
|
||||
if err != nil {
|
||||
slog.Error("db: failed to delete channel", "error", err)
|
||||
return fmt.Errorf("failed to delete channel")
|
||||
}
|
||||
|
||||
slog.Debug("db: channel deleted")
|
||||
return nil
|
||||
}
|
||||
|
@@ -41,21 +41,3 @@ func NewUserListResponse(users []*User) []render.Renderer {
|
||||
func NewUserPayloadResponse(user *User) *UserPayload {
|
||||
return &UserPayload{User: user}
|
||||
}
|
||||
|
||||
func NewChannelResponse(channel *Channel) *ChannelResponse {
|
||||
resp := &ChannelResponse{Channel: channel}
|
||||
|
||||
return resp
|
||||
}
|
||||
|
||||
func (cr *ChannelResponse) Render(w http.ResponseWriter, r *http.Request) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewChannelListResponse(channels []*Channel) []render.Renderer {
|
||||
list := []render.Renderer{}
|
||||
for _, channel := range channels {
|
||||
list = append(list, NewChannelResponse(channel))
|
||||
}
|
||||
return list
|
||||
}
|
||||
|
4
example_client/svelte-client/.gitignore
vendored
Normal file
4
example_client/svelte-client/.gitignore
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
/node_modules/
|
||||
/public/build/
|
||||
|
||||
.DS_Store
|
107
example_client/svelte-client/README.md
Normal file
107
example_client/svelte-client/README.md
Normal file
@@ -0,0 +1,107 @@
|
||||
# This repo is no longer maintained. Consider using `npm init vite` and selecting the `svelte` option or — if you want a full-fledged app framework — use [SvelteKit](https://kit.svelte.dev), the official application framework for Svelte.
|
||||
|
||||
---
|
||||
|
||||
# svelte app
|
||||
|
||||
This is a project template for [Svelte](https://svelte.dev) apps. It lives at https://github.com/sveltejs/template.
|
||||
|
||||
To create a new project based on this template using [degit](https://github.com/Rich-Harris/degit):
|
||||
|
||||
```bash
|
||||
npx degit sveltejs/template svelte-app
|
||||
cd svelte-app
|
||||
```
|
||||
|
||||
*Note that you will need to have [Node.js](https://nodejs.org) installed.*
|
||||
|
||||
|
||||
## Get started
|
||||
|
||||
Install the dependencies...
|
||||
|
||||
```bash
|
||||
cd svelte-app
|
||||
npm install
|
||||
```
|
||||
|
||||
...then start [Rollup](https://rollupjs.org):
|
||||
|
||||
```bash
|
||||
npm run dev
|
||||
```
|
||||
|
||||
Navigate to [localhost:8080](http://localhost:8080). You should see your app running. Edit a component file in `src`, save it, and reload the page to see your changes.
|
||||
|
||||
By default, the server will only respond to requests from localhost. To allow connections from other computers, edit the `sirv` commands in package.json to include the option `--host 0.0.0.0`.
|
||||
|
||||
If you're using [Visual Studio Code](https://code.visualstudio.com/) we recommend installing the official extension [Svelte for VS Code](https://marketplace.visualstudio.com/items?itemName=svelte.svelte-vscode). If you are using other editors you may need to install a plugin in order to get syntax highlighting and intellisense.
|
||||
|
||||
## Building and running in production mode
|
||||
|
||||
To create an optimised version of the app:
|
||||
|
||||
```bash
|
||||
npm run build
|
||||
```
|
||||
|
||||
You can run the newly built app with `npm run start`. This uses [sirv](https://github.com/lukeed/sirv), which is included in your package.json's `dependencies` so that the app will work when you deploy to platforms like [Heroku](https://heroku.com).
|
||||
|
||||
|
||||
## Single-page app mode
|
||||
|
||||
By default, sirv will only respond to requests that match files in `public`. This is to maximise compatibility with static fileservers, allowing you to deploy your app anywhere.
|
||||
|
||||
If you're building a single-page app (SPA) with multiple routes, sirv needs to be able to respond to requests for *any* path. You can make it so by editing the `"start"` command in package.json:
|
||||
|
||||
```js
|
||||
"start": "sirv public --single"
|
||||
```
|
||||
|
||||
## Using TypeScript
|
||||
|
||||
This template comes with a script to set up a TypeScript development environment, you can run it immediately after cloning the template with:
|
||||
|
||||
```bash
|
||||
node scripts/setupTypeScript.js
|
||||
```
|
||||
|
||||
Or remove the script via:
|
||||
|
||||
```bash
|
||||
rm scripts/setupTypeScript.js
|
||||
```
|
||||
|
||||
If you want to use `baseUrl` or `path` aliases within your `tsconfig`, you need to set up `@rollup/plugin-alias` to tell Rollup to resolve the aliases. For more info, see [this StackOverflow question](https://stackoverflow.com/questions/63427935/setup-tsconfig-path-in-svelte).
|
||||
|
||||
## Deploying to the web
|
||||
|
||||
### With [Vercel](https://vercel.com)
|
||||
|
||||
Install `vercel` if you haven't already:
|
||||
|
||||
```bash
|
||||
npm install -g vercel
|
||||
```
|
||||
|
||||
Then, from within your project folder:
|
||||
|
||||
```bash
|
||||
cd public
|
||||
vercel deploy --name my-project
|
||||
```
|
||||
|
||||
### With [surge](https://surge.sh/)
|
||||
|
||||
Install `surge` if you haven't already:
|
||||
|
||||
```bash
|
||||
npm install -g surge
|
||||
```
|
||||
|
||||
Then, from within your project folder:
|
||||
|
||||
```bash
|
||||
npm run build
|
||||
surge public my-project.surge.sh
|
||||
```
|
1349
example_client/svelte-client/package-lock.json
generated
Normal file
1349
example_client/svelte-client/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
26
example_client/svelte-client/package.json
Normal file
26
example_client/svelte-client/package.json
Normal file
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"name": "svelte-app",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "rollup -c",
|
||||
"dev": "rollup -c -w",
|
||||
"start": "sirv public --single"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@rollup/plugin-commonjs": "^24.0.0",
|
||||
"@rollup/plugin-node-resolve": "^15.0.0",
|
||||
"@rollup/plugin-terser": "^0.4.0",
|
||||
"rollup": "^3.15.0",
|
||||
"rollup-plugin-css-only": "^4.3.0",
|
||||
"rollup-plugin-livereload": "^2.0.0",
|
||||
"rollup-plugin-svelte": "^7.1.2",
|
||||
"svelte": "^3.55.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"axios": "^1.9.0",
|
||||
"sirv-cli": "^2.0.0",
|
||||
"svelte-spa-router": "^4.0.1"
|
||||
}
|
||||
}
|
BIN
example_client/svelte-client/public/favicon.png
Normal file
BIN
example_client/svelte-client/public/favicon.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 3.1 KiB |
63
example_client/svelte-client/public/global.css
Normal file
63
example_client/svelte-client/public/global.css
Normal file
@@ -0,0 +1,63 @@
|
||||
html, body {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
body {
|
||||
color: #333;
|
||||
margin: 0;
|
||||
padding: 8px;
|
||||
box-sizing: border-box;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
|
||||
}
|
||||
|
||||
a {
|
||||
color: rgb(0,100,200);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
a:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
a:visited {
|
||||
color: rgb(0,80,160);
|
||||
}
|
||||
|
||||
label {
|
||||
display: block;
|
||||
}
|
||||
|
||||
input, button, select, textarea {
|
||||
font-family: inherit;
|
||||
font-size: inherit;
|
||||
-webkit-padding: 0.4em 0;
|
||||
padding: 0.4em;
|
||||
margin: 0 0 0.5em 0;
|
||||
box-sizing: border-box;
|
||||
border: 1px solid #ccc;
|
||||
border-radius: 2px;
|
||||
}
|
||||
|
||||
input:disabled {
|
||||
color: #ccc;
|
||||
}
|
||||
|
||||
button {
|
||||
color: #333;
|
||||
background-color: #f4f4f4;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
button:disabled {
|
||||
color: #999;
|
||||
}
|
||||
|
||||
button:not(:disabled):active {
|
||||
background-color: #ddd;
|
||||
}
|
||||
|
||||
button:focus {
|
||||
border-color: #666;
|
||||
}
|
18
example_client/svelte-client/public/index.html
Normal file
18
example_client/svelte-client/public/index.html
Normal file
@@ -0,0 +1,18 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset='utf-8'>
|
||||
<meta name='viewport' content='width=device-width,initial-scale=1'>
|
||||
|
||||
<title>Svelte app</title>
|
||||
|
||||
<link rel='icon' type='image/png' href='/favicon.png'>
|
||||
<link rel='stylesheet' href='/global.css'>
|
||||
<link rel='stylesheet' href='/build/bundle.css'>
|
||||
|
||||
<script defer src='/build/bundle.js'></script>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
</body>
|
||||
</html>
|
78
example_client/svelte-client/rollup.config.js
Normal file
78
example_client/svelte-client/rollup.config.js
Normal file
@@ -0,0 +1,78 @@
|
||||
import { spawn } from 'child_process';
|
||||
import svelte from 'rollup-plugin-svelte';
|
||||
import commonjs from '@rollup/plugin-commonjs';
|
||||
import terser from '@rollup/plugin-terser';
|
||||
import resolve from '@rollup/plugin-node-resolve';
|
||||
import livereload from 'rollup-plugin-livereload';
|
||||
import css from 'rollup-plugin-css-only';
|
||||
|
||||
const production = !process.env.ROLLUP_WATCH;
|
||||
|
||||
function serve() {
|
||||
let server;
|
||||
|
||||
function toExit() {
|
||||
if (server) server.kill(0);
|
||||
}
|
||||
|
||||
return {
|
||||
writeBundle() {
|
||||
if (server) return;
|
||||
server = spawn('npm', ['run', 'start', '--', '--dev'], {
|
||||
stdio: ['ignore', 'inherit', 'inherit'],
|
||||
shell: true
|
||||
});
|
||||
|
||||
process.on('SIGTERM', toExit);
|
||||
process.on('exit', toExit);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export default {
|
||||
input: 'src/main.js',
|
||||
output: {
|
||||
sourcemap: true,
|
||||
format: 'iife',
|
||||
name: 'app',
|
||||
file: 'public/build/bundle.js'
|
||||
},
|
||||
plugins: [
|
||||
svelte({
|
||||
compilerOptions: {
|
||||
// enable run-time checks when not in production
|
||||
dev: !production
|
||||
}
|
||||
}),
|
||||
// we'll extract any component CSS out into
|
||||
// a separate file - better for performance
|
||||
css({ output: 'bundle.css' }),
|
||||
|
||||
// If you have external dependencies installed from
|
||||
// npm, you'll most likely need these plugins. In
|
||||
// some cases you'll need additional configuration -
|
||||
// consult the documentation for details:
|
||||
// https://github.com/rollup/plugins/tree/master/packages/commonjs
|
||||
resolve({
|
||||
browser: true,
|
||||
dedupe: ['svelte'],
|
||||
exportConditions: ['svelte']
|
||||
}),
|
||||
commonjs(),
|
||||
|
||||
// In dev mode, call `npm run start` once
|
||||
// the bundle has been generated
|
||||
!production && serve(),
|
||||
|
||||
// Watch the `public` directory and refresh the
|
||||
// browser on changes when not in production
|
||||
!production && livereload('public'),
|
||||
|
||||
// If we're building for production (npm run build
|
||||
// instead of npm run dev), minify
|
||||
production && terser()
|
||||
],
|
||||
watch: {
|
||||
clearScreen: false
|
||||
}
|
||||
};
|
134
example_client/svelte-client/scripts/setupTypeScript.js
Normal file
134
example_client/svelte-client/scripts/setupTypeScript.js
Normal file
@@ -0,0 +1,134 @@
|
||||
// @ts-check
|
||||
|
||||
/** This script modifies the project to support TS code in .svelte files like:
|
||||
|
||||
<script lang="ts">
|
||||
export let name: string;
|
||||
</script>
|
||||
|
||||
As well as validating the code for CI.
|
||||
*/
|
||||
|
||||
/** To work on this script:
|
||||
rm -rf test-template template && git clone sveltejs/template test-template && node scripts/setupTypeScript.js test-template
|
||||
*/
|
||||
|
||||
import fs from "fs"
|
||||
import path from "path"
|
||||
import { argv } from "process"
|
||||
import url from 'url';
|
||||
|
||||
const __filename = url.fileURLToPath(import.meta.url);
|
||||
const __dirname = url.fileURLToPath(new URL('.', import.meta.url));
|
||||
const projectRoot = argv[2] || path.join(__dirname, "..")
|
||||
|
||||
// Add deps to pkg.json
|
||||
const packageJSON = JSON.parse(fs.readFileSync(path.join(projectRoot, "package.json"), "utf8"))
|
||||
packageJSON.devDependencies = Object.assign(packageJSON.devDependencies, {
|
||||
"svelte-check": "^3.0.0",
|
||||
"svelte-preprocess": "^5.0.0",
|
||||
"@rollup/plugin-typescript": "^11.0.0",
|
||||
"typescript": "^4.9.0",
|
||||
"tslib": "^2.5.0",
|
||||
"@tsconfig/svelte": "^3.0.0"
|
||||
})
|
||||
|
||||
// Add script for checking
|
||||
packageJSON.scripts = Object.assign(packageJSON.scripts, {
|
||||
"check": "svelte-check"
|
||||
})
|
||||
|
||||
// Write the package JSON
|
||||
fs.writeFileSync(path.join(projectRoot, "package.json"), JSON.stringify(packageJSON, null, " "))
|
||||
|
||||
// mv src/main.js to main.ts - note, we need to edit rollup.config.js for this too
|
||||
const beforeMainJSPath = path.join(projectRoot, "src", "main.js")
|
||||
const afterMainTSPath = path.join(projectRoot, "src", "main.ts")
|
||||
fs.renameSync(beforeMainJSPath, afterMainTSPath)
|
||||
|
||||
// Switch the app.svelte file to use TS
|
||||
const appSveltePath = path.join(projectRoot, "src", "App.svelte")
|
||||
let appFile = fs.readFileSync(appSveltePath, "utf8")
|
||||
appFile = appFile.replace("<script>", '<script lang="ts">')
|
||||
appFile = appFile.replace("export let name;", 'export let name: string;')
|
||||
fs.writeFileSync(appSveltePath, appFile)
|
||||
|
||||
// Edit rollup config
|
||||
const rollupConfigPath = path.join(projectRoot, "rollup.config.js")
|
||||
let rollupConfig = fs.readFileSync(rollupConfigPath, "utf8")
|
||||
|
||||
// Edit imports
|
||||
rollupConfig = rollupConfig.replace(`'rollup-plugin-css-only';`, `'rollup-plugin-css-only';
|
||||
import sveltePreprocess from 'svelte-preprocess';
|
||||
import typescript from '@rollup/plugin-typescript';`)
|
||||
|
||||
// Replace name of entry point
|
||||
rollupConfig = rollupConfig.replace(`'src/main.js'`, `'src/main.ts'`)
|
||||
|
||||
// Add preprocessor
|
||||
rollupConfig = rollupConfig.replace(
|
||||
'compilerOptions:',
|
||||
'preprocess: sveltePreprocess({ sourceMap: !production }),\n\t\t\tcompilerOptions:'
|
||||
);
|
||||
|
||||
// Add TypeScript
|
||||
rollupConfig = rollupConfig.replace(
|
||||
'commonjs(),',
|
||||
'commonjs(),\n\t\ttypescript({\n\t\t\tsourceMap: !production,\n\t\t\tinlineSources: !production\n\t\t}),'
|
||||
);
|
||||
fs.writeFileSync(rollupConfigPath, rollupConfig)
|
||||
|
||||
// Add svelte.config.js
|
||||
const tsconfig = `{
|
||||
"extends": "@tsconfig/svelte/tsconfig.json",
|
||||
|
||||
"include": ["src/**/*"],
|
||||
"exclude": ["node_modules/*", "__sapper__/*", "public/*"]
|
||||
}`
|
||||
const tsconfigPath = path.join(projectRoot, "tsconfig.json")
|
||||
fs.writeFileSync(tsconfigPath, tsconfig)
|
||||
|
||||
// Add TSConfig
|
||||
const svelteConfig = `import sveltePreprocess from 'svelte-preprocess';
|
||||
|
||||
export default {
|
||||
preprocess: sveltePreprocess()
|
||||
};
|
||||
`
|
||||
const svelteConfigPath = path.join(projectRoot, "svelte.config.js")
|
||||
fs.writeFileSync(svelteConfigPath, svelteConfig)
|
||||
|
||||
// Add global.d.ts
|
||||
const dtsPath = path.join(projectRoot, "src", "global.d.ts")
|
||||
fs.writeFileSync(dtsPath, `/// <reference types="svelte" />`)
|
||||
|
||||
// Delete this script, but not during testing
|
||||
if (!argv[2]) {
|
||||
// Remove the script
|
||||
fs.unlinkSync(path.join(__filename))
|
||||
|
||||
// Check for Mac's DS_store file, and if it's the only one left remove it
|
||||
const remainingFiles = fs.readdirSync(path.join(__dirname))
|
||||
if (remainingFiles.length === 1 && remainingFiles[0] === '.DS_store') {
|
||||
fs.unlinkSync(path.join(__dirname, '.DS_store'))
|
||||
}
|
||||
|
||||
// Check if the scripts folder is empty
|
||||
if (fs.readdirSync(path.join(__dirname)).length === 0) {
|
||||
// Remove the scripts folder
|
||||
fs.rmdirSync(path.join(__dirname))
|
||||
}
|
||||
}
|
||||
|
||||
// Adds the extension recommendation
|
||||
fs.mkdirSync(path.join(projectRoot, ".vscode"), { recursive: true })
|
||||
fs.writeFileSync(path.join(projectRoot, ".vscode", "extensions.json"), `{
|
||||
"recommendations": ["svelte.svelte-vscode"]
|
||||
}
|
||||
`)
|
||||
|
||||
console.log("Converted to TypeScript.")
|
||||
|
||||
if (fs.existsSync(path.join(projectRoot, "node_modules"))) {
|
||||
console.log("\nYou will need to re-run your dependency manager to get started.")
|
||||
}
|
6
example_client/svelte-client/src/App.svelte
Normal file
6
example_client/svelte-client/src/App.svelte
Normal file
@@ -0,0 +1,6 @@
|
||||
<script>
|
||||
import Router from 'svelte-spa-router';
|
||||
import routes from './routes.js';
|
||||
</script>
|
||||
|
||||
<Router {routes} />
|
36
example_client/svelte-client/src/api.js
Normal file
36
example_client/svelte-client/src/api.js
Normal file
@@ -0,0 +1,36 @@
|
||||
import axios from 'axios';
|
||||
|
||||
const API_BASE_URL = 'http://localhost:3000';
|
||||
|
||||
export const login = async (username, password) => {
|
||||
const formData = new FormData();
|
||||
formData.append('username', username);
|
||||
formData.append('password', password);
|
||||
|
||||
const response = await axios.post(`${API_BASE_URL}/login`, formData, {
|
||||
headers: {
|
||||
'Content-Type': 'multipart/form-data',
|
||||
},
|
||||
withCredentials: true,
|
||||
});
|
||||
|
||||
return response.data;
|
||||
};
|
||||
|
||||
export const fetchMessages = async () => {
|
||||
const response = await axios.get(`${API_BASE_URL}/messages`, { withCredentials: true });
|
||||
return response.data;
|
||||
};
|
||||
|
||||
export const createMessage = async (body) => {
|
||||
const formData = new FormData();
|
||||
formData.append('body', body);
|
||||
|
||||
const response = await axios.post(`${API_BASE_URL}/messages/new`, formData, {
|
||||
headers: {
|
||||
'Content-Type': 'multipart/form-data',
|
||||
},
|
||||
withCredentials: true,
|
||||
});
|
||||
return response.data;
|
||||
};
|
10
example_client/svelte-client/src/main.js
Normal file
10
example_client/svelte-client/src/main.js
Normal file
@@ -0,0 +1,10 @@
|
||||
import App from './App.svelte';
|
||||
|
||||
const app = new App({
|
||||
target: document.body,
|
||||
props: {
|
||||
name: 'world'
|
||||
}
|
||||
});
|
||||
|
||||
export default app;
|
7
example_client/svelte-client/src/routes.js
Normal file
7
example_client/svelte-client/src/routes.js
Normal file
@@ -0,0 +1,7 @@
|
||||
import Login from './routes/Login.svelte';
|
||||
import Messages from './routes/Messages.svelte';
|
||||
|
||||
export default {
|
||||
'/': Login,
|
||||
'/messages': Messages,
|
||||
};
|
22
example_client/svelte-client/src/routes/Login.svelte
Normal file
22
example_client/svelte-client/src/routes/Login.svelte
Normal file
@@ -0,0 +1,22 @@
|
||||
<script>
|
||||
import { login } from '../api.js';
|
||||
import { push } from 'svelte-spa-router';
|
||||
let username = '';
|
||||
let password = '';
|
||||
let error = '';
|
||||
|
||||
const handleLogin = async () => {
|
||||
try {
|
||||
await login(username, password);
|
||||
push('/messages');
|
||||
} catch (err) {
|
||||
error = err;
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
<h1>Login</h1>
|
||||
<input type="text" bind:value={username} placeholder="Username" />
|
||||
<input type="password" bind:value={password} placeholder="Password" />
|
||||
<button on:click={handleLogin}>Login</button>
|
||||
<p style="color: red">{error}</p>
|
26
example_client/svelte-client/src/routes/Messages.svelte
Normal file
26
example_client/svelte-client/src/routes/Messages.svelte
Normal file
@@ -0,0 +1,26 @@
|
||||
<script>
|
||||
import { fetchMessages, createMessage } from '../api.js';
|
||||
let messages = [];
|
||||
let newMessage = '';
|
||||
|
||||
const loadMessages = async () => {
|
||||
messages = await fetchMessages();
|
||||
};
|
||||
|
||||
const handleCreateMessage = async () => {
|
||||
await createMessage(newMessage);
|
||||
newMessage = '';
|
||||
await loadMessages();
|
||||
};
|
||||
|
||||
loadMessages();
|
||||
</script>
|
||||
|
||||
<h1>Messages</h1>
|
||||
<ul>
|
||||
{#each messages as message}
|
||||
<li>{message.user.name} - {message.body} - {message.timestamp}</li>
|
||||
{/each}
|
||||
</ul>
|
||||
<input type="text" bind:value={newMessage} placeholder="New message" />
|
||||
<button on:click={handleCreateMessage}>Send</button>
|
Reference in New Issue
Block a user