Add note scaffold
This commit is contained in:
@@ -0,0 +1,108 @@
|
||||
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>{% block title %}{% endblock title %}</title>
|
||||
|
||||
<script src="https://unpkg.com/htmx.org@2.0.0/dist/htmx.min.js"></script>
|
||||
<script src="https://cdn.tailwindcss.com?plugins=forms,typography,aspect-ratio,line-clamp"></script>
|
||||
{% block head %}
|
||||
|
||||
{% endblock head %}
|
||||
</head>
|
||||
|
||||
<body class="min-h-screen bg-background font-sans antialiased">
|
||||
<div class="relative flex min-h-screen flex-col bg-background">
|
||||
<div class="themes-wrapper bg-background">
|
||||
<main>
|
||||
<div class="flex flex-1 flex-col gap-4 p-5 pt-5">
|
||||
<h1 class="scroll-m-20 text-3xl font-bold tracking-tight">
|
||||
{% block page_title %}{% endblock page_title %}
|
||||
</h1>
|
||||
{% block content %}
|
||||
{% endblock content %}
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
{% block js %}
|
||||
|
||||
{% endblock js %}
|
||||
|
||||
<script>
|
||||
htmx.defineExtension('submitjson', {
|
||||
onEvent: function (name, evt) {
|
||||
if (name === "htmx:configRequest") {
|
||||
evt.detail.headers['Content-Type'] = "application/json"
|
||||
}
|
||||
},
|
||||
encodeParameters: function (xhr, parameters, elt) {
|
||||
const json = {};
|
||||
for (const [key, inputValue] of Object.entries(parameters)) {
|
||||
let origInputType = elt.querySelector(`[name=${key}]`).type;
|
||||
const customType = elt.querySelector(`[name=${key}]`).getAttribute("custom_type");
|
||||
|
||||
let value = inputValue;
|
||||
if (customType == "array" && !Array.isArray(inputValue)) {
|
||||
value = [inputValue]
|
||||
}
|
||||
|
||||
if (origInputType === 'number') {
|
||||
if (Array.isArray(value)) {
|
||||
json[key] = Object.values(value).map(str => parseFloat(str))
|
||||
} else {
|
||||
json[key] = parseFloat(value)
|
||||
}
|
||||
} else if (origInputType === 'checkbox') {
|
||||
const val = elt.querySelector(`[name=${key}]`).checked;
|
||||
json[key] = val
|
||||
} else if (customType === 'blob') {
|
||||
json[key] = value.split(",").map(num => parseInt(num, 10));
|
||||
} else {
|
||||
json[key] = value;
|
||||
}
|
||||
}
|
||||
return JSON.stringify(json);
|
||||
}
|
||||
})
|
||||
function confirmDelete(event, delete_url, redirect_to) {
|
||||
event.preventDefault();
|
||||
if (confirm("Are you sure you want to delete this item?")) {
|
||||
var xhr = new XMLHttpRequest();
|
||||
xhr.open("DELETE", delete_url, true);
|
||||
xhr.onreadystatechange = function () {
|
||||
if (xhr.readyState == 4 && xhr.status == 200) {
|
||||
window.location.href = redirect_to;
|
||||
}
|
||||
};
|
||||
xhr.send();
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
document.querySelectorAll('.add-more').forEach(button => {
|
||||
button.addEventListener('click', function () {
|
||||
const group = this.getAttribute('data-group');
|
||||
const first = document.getElementById(`${group}-inputs`).querySelector('input');
|
||||
if (first) {
|
||||
const clonedInput = first.cloneNode();
|
||||
clonedInput.value = '';
|
||||
const container = document.getElementById(`${group}-inputs`);
|
||||
container.appendChild(clonedInput);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
document.body.addEventListener('htmx:responseError', function (event) {
|
||||
const target = document.querySelector('#error-message');
|
||||
const errorResponse = event.detail.xhr.response;
|
||||
target.innerHTML = errorResponse
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -0,0 +1,37 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}
|
||||
Create note
|
||||
{% endblock title %}
|
||||
|
||||
{% block page_title %}
|
||||
Create new note
|
||||
{% endblock page_title %}
|
||||
|
||||
{% block content %}
|
||||
<div class="mb-10">
|
||||
<div id="error-message" class="mt-4 text-sm text-red-600"></div>
|
||||
<form hx-post="/notes" hx-ext="submitjson" class="flex-1 lg:max-w-2xl">
|
||||
<div class="space-y-2">
|
||||
<label class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70" for=":r2l:-form-item">user_id</label>
|
||||
<input class="flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-sm md:text-sm" min="-2147483648" max="2147483647" id="user_id" name="user_id" type="number" value="" step="1" />
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<label class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70" for=":r2l:-form-item">title</label>
|
||||
<input class="flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-sm md:text-sm" id="title" name="title" type="text" value="" />
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<label class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70" for=":r2l:-form-item">content</label>
|
||||
<input class="flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-sm md:text-sm" id="content" name="content" type="text" value="" />
|
||||
</div>
|
||||
<div class="mt-5">
|
||||
<button class=" text-xs py-3 px-6 rounded-lg bg-gray-900 text-white" type="submit">Submit</button>
|
||||
</div>
|
||||
|
||||
</form>
|
||||
</div>
|
||||
{% endblock content %}
|
||||
|
||||
{% block js %}
|
||||
|
||||
{% endblock js %}
|
||||
@@ -0,0 +1,43 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}
|
||||
Edit note: {{ item.id }}
|
||||
{% endblock title %}
|
||||
|
||||
{% block page_title %}
|
||||
Edit note: {{ item.id }}
|
||||
{% endblock page_title %}
|
||||
|
||||
{% block content %}
|
||||
<div class="mb-10">
|
||||
<div id="error-message" class="mt-4 text-sm text-red-600"></div>
|
||||
<form hx-put="/notes/{{ item.id }}" hx-ext="submitjson" hx-target="#success-message" class="flex-1 lg:max-w-2xl">
|
||||
<div class="space-y-2">
|
||||
<label class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70" for=":r2l:-form-item">user_id</label>
|
||||
<input class="flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-sm md:text-sm" min="-2147483648" max="2147483647" id="user_id" name="user_id" type="number" value="{{item.user_id}}" step="1" />
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<label class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70" for=":r2l:-form-item">title</label>
|
||||
<input class="flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-sm md:text-sm" id="title" name="title" type="text" value="{{item.title}}" />
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<label class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70" for=":r2l:-form-item">content</label>
|
||||
<input class="flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-sm md:text-sm" id="content" name="content" type="text" value="{{item.content}}" />
|
||||
</div>
|
||||
<div>
|
||||
<div class="mt-5">
|
||||
<button class=" text-xs py-3 px-6 rounded-lg bg-gray-900 text-white" type="submit">Submit</button>
|
||||
<button class="text-xs py-3 px-6 rounded-lg bg-red-600 text-white"
|
||||
onclick="confirmDelete(event, '/notes/{{ item.id }}', '/notes' )">Delete</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
<div id="success-message" class="mt-4"></div>
|
||||
<br />
|
||||
<a href="/notes">Back to note</a>
|
||||
</div>
|
||||
{% endblock content %}
|
||||
|
||||
{% block js %}
|
||||
|
||||
{% endblock js %}
|
||||
@@ -0,0 +1,86 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}
|
||||
List of note
|
||||
{% endblock title %}
|
||||
|
||||
{% block page_title %}
|
||||
note
|
||||
{% endblock page_title %}
|
||||
|
||||
{% block content %}
|
||||
<div class="mb-10">
|
||||
|
||||
{% if items %}
|
||||
|
||||
<div class="mb-5">
|
||||
<div class="relative w-full overflow-auto">
|
||||
<table class="w-full caption-bottom text-sm">
|
||||
<thead class="[&_tr]:border-b">
|
||||
<tr class="border-b transition-colors hover:bg-muted/50">
|
||||
<th class="h-10 px-2 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px] w-[100px]">
|
||||
{{"user_id" | capitalize }}
|
||||
</th>
|
||||
<th class="h-10 px-2 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px] w-[100px]">
|
||||
{{"title" | capitalize }}
|
||||
</th>
|
||||
<th class="h-10 px-2 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px] w-[100px]">
|
||||
{{"content" | capitalize }}
|
||||
</th>
|
||||
<th class="h-10 px-2 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px] w-[100px]">
|
||||
Actions
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="[&_tr:last-child]:border-0">
|
||||
{% for item in items %}
|
||||
<tr class="border-b transition-colors hover:bg-muted/50">
|
||||
<td
|
||||
class="p-2 align-middle font-medium">
|
||||
{{item.user_id | escape }}
|
||||
</td>
|
||||
<td
|
||||
class="p-2 align-middle font-medium">
|
||||
{{item.title | escape }}
|
||||
</td>
|
||||
<td
|
||||
class="p-2 align-middle font-medium">
|
||||
{{item.content | escape }}
|
||||
</td>
|
||||
<td>
|
||||
<a href="/notes/{{ item.id }}/edit">Edit</a>
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="flex">
|
||||
<div class="ml-auto p-4">
|
||||
<a href="/notes/new"
|
||||
class="mt-5 bg-blue-500 text-white bg-primary-600 hover:bg-primary-700 focus:ring-4 focus:outline-none focus:ring-primary-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-primary-600 dark:hover:bg-primary-700 dark:focus:ring-primary-800">
|
||||
Create
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% else %}
|
||||
|
||||
<div class="mt-10 flex items-center justify-center">
|
||||
<div class="bg-white rounded-lg shadow-lg p-8 max-w-4xl w-full flex flex-col items-center">
|
||||
<h3 class="font-bold text-lg">Nothing Here Yet</h3>
|
||||
There are no records to display. Add a new record to get started!
|
||||
<a href="/notes/new"
|
||||
class="mt-5 bg-blue-500 text-white bg-primary-600 hover:bg-primary-700 focus:ring-4 focus:outline-none focus:ring-primary-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-primary-600 dark:hover:bg-primary-700 dark:focus:ring-primary-800">
|
||||
Create
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% endif %}
|
||||
|
||||
|
||||
</div>
|
||||
{% endblock content %}
|
||||
@@ -0,0 +1,26 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}
|
||||
View note: {{ item.id }}
|
||||
{% endblock title %}
|
||||
|
||||
{% block page_title %}
|
||||
View note: {{ item.id }}
|
||||
{% endblock page_title %}
|
||||
|
||||
|
||||
{% block content %}
|
||||
<div class="mb-10">
|
||||
<div>
|
||||
<label><b>{{"user_id" | capitalize }}:</b> {{item.user_id}}</label>
|
||||
</div>
|
||||
<div>
|
||||
<label><b>{{"title" | capitalize }}:</b> {{item.title}}</label>
|
||||
</div>
|
||||
<div>
|
||||
<label><b>{{"content" | capitalize }}:</b> {{item.content}}</label>
|
||||
</div>
|
||||
<br />
|
||||
<a href="/notes">Back to notes</a>
|
||||
</div>
|
||||
{% endblock content %}
|
||||
@@ -3,6 +3,7 @@
|
||||
pub use sea_orm_migration::prelude::*;
|
||||
mod m20220101_000001_users;
|
||||
|
||||
mod m20260726_113842_notes;
|
||||
pub struct Migrator;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
@@ -10,7 +11,8 @@ impl MigratorTrait for Migrator {
|
||||
fn migrations() -> Vec<Box<dyn MigrationTrait>> {
|
||||
vec![
|
||||
Box::new(m20220101_000001_users::Migration),
|
||||
Box::new(m20260726_113842_notes::Migration),
|
||||
// inject-above (do not remove this comment)
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
use loco_rs::schema::*;
|
||||
use sea_orm_migration::prelude::*;
|
||||
|
||||
#[derive(DeriveMigrationName)]
|
||||
pub struct Migration;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl MigrationTrait for Migration {
|
||||
async fn up(&self, m: &SchemaManager) -> Result<(), DbErr> {
|
||||
create_table(m, "notes",
|
||||
&[
|
||||
|
||||
("id", ColType::PkAuto),
|
||||
|
||||
("title", ColType::StringNull),
|
||||
("content", ColType::TextNull),
|
||||
],
|
||||
&[
|
||||
("user", ""),
|
||||
]
|
||||
).await
|
||||
}
|
||||
|
||||
async fn down(&self, m: &SchemaManager) -> Result<(), DbErr> {
|
||||
drop_table(m, "notes").await
|
||||
}
|
||||
}
|
||||
@@ -51,6 +51,7 @@ impl Hooks for App {
|
||||
|
||||
fn routes(_ctx: &AppContext) -> AppRoutes {
|
||||
AppRoutes::with_default_routes() // controller routes below
|
||||
.add_route(controllers::note::routes())
|
||||
.add_route(controllers::auth::routes())
|
||||
}
|
||||
async fn connect_workers(ctx: &AppContext, queue: &Queue) -> Result<()> {
|
||||
@@ -71,4 +72,4 @@ impl Hooks for App {
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1 +1,3 @@
|
||||
pub mod auth;
|
||||
|
||||
pub mod note;
|
||||
@@ -0,0 +1,113 @@
|
||||
#![allow(clippy::missing_errors_doc)]
|
||||
#![allow(clippy::unnecessary_struct_initialization)]
|
||||
#![allow(clippy::unused_async)]
|
||||
use loco_rs::prelude::*;
|
||||
use sea_orm::{sea_query::Order, QueryOrder};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{
|
||||
models::_entities::notes::{ActiveModel, Column, Entity, Model},
|
||||
views,
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct Params {
|
||||
pub user_id: i64,
|
||||
pub title: Option<String>,
|
||||
pub content: Option<String>,
|
||||
}
|
||||
|
||||
impl Params {
|
||||
fn update(&self, item: &mut ActiveModel) {
|
||||
item.user_id = Set(self.user_id);
|
||||
item.title = Set(self.title.clone());
|
||||
item.content = Set(self.content.clone());
|
||||
}
|
||||
}
|
||||
|
||||
async fn load_item(ctx: &AppContext, id: i64) -> Result<Model> {
|
||||
let item = Entity::find_by_id(id).one(&ctx.db).await?;
|
||||
item.ok_or_else(|| Error::NotFound)
|
||||
}
|
||||
|
||||
#[debug_handler]
|
||||
pub async fn list(
|
||||
ViewEngine(v): ViewEngine<TeraView>,
|
||||
State(ctx): State<AppContext>,
|
||||
) -> Result<Response> {
|
||||
let item = Entity::find()
|
||||
.order_by(Column::Id, Order::Desc)
|
||||
.all(&ctx.db)
|
||||
.await?;
|
||||
views::note::list(&v, &item)
|
||||
}
|
||||
|
||||
#[debug_handler]
|
||||
pub async fn new(
|
||||
ViewEngine(v): ViewEngine<TeraView>,
|
||||
State(_ctx): State<AppContext>,
|
||||
) -> Result<Response> {
|
||||
views::note::create(&v)
|
||||
}
|
||||
|
||||
#[debug_handler]
|
||||
pub async fn update(
|
||||
Path(id): Path<i64>,
|
||||
State(ctx): State<AppContext>,
|
||||
Json(params): Json<Params>,
|
||||
) -> Result<Response> {
|
||||
let item = load_item(&ctx, id).await?;
|
||||
let mut item = item.into_active_model();
|
||||
params.update(&mut item);
|
||||
let _ = item.update(&ctx.db).await?;
|
||||
format::render().redirect_with_header_key("HX-Redirect", "/notes")
|
||||
}
|
||||
|
||||
#[debug_handler]
|
||||
pub async fn edit(
|
||||
Path(id): Path<i64>,
|
||||
ViewEngine(v): ViewEngine<TeraView>,
|
||||
State(ctx): State<AppContext>,
|
||||
) -> Result<Response> {
|
||||
let item = load_item(&ctx, id).await?;
|
||||
views::note::edit(&v, &item)
|
||||
}
|
||||
|
||||
#[debug_handler]
|
||||
pub async fn show(
|
||||
Path(id): Path<i64>,
|
||||
ViewEngine(v): ViewEngine<TeraView>,
|
||||
State(ctx): State<AppContext>,
|
||||
) -> Result<Response> {
|
||||
let item = load_item(&ctx, id).await?;
|
||||
views::note::show(&v, &item)
|
||||
}
|
||||
|
||||
#[debug_handler]
|
||||
pub async fn add(State(ctx): State<AppContext>, Json(params): Json<Params>) -> Result<Response> {
|
||||
let mut item = ActiveModel {
|
||||
..Default::default()
|
||||
};
|
||||
params.update(&mut item);
|
||||
let _ = item.insert(&ctx.db).await?;
|
||||
format::render().redirect_with_header_key("HX-Redirect", "/notes")
|
||||
}
|
||||
|
||||
#[debug_handler]
|
||||
pub async fn remove(Path(id): Path<i64>, State(ctx): State<AppContext>) -> Result<Response> {
|
||||
load_item(&ctx, id).await?.delete(&ctx.db).await?;
|
||||
format::empty()
|
||||
}
|
||||
|
||||
pub fn routes() -> Routes {
|
||||
Routes::new()
|
||||
.prefix("notes/")
|
||||
.add("/", get(list))
|
||||
.add("/", post(add))
|
||||
.add("new", get(new))
|
||||
.add("{id}", get(show))
|
||||
.add("{id}/edit", get(edit))
|
||||
.add("{id}", delete(remove))
|
||||
.add("{id}", put(update))
|
||||
.add("{id}", patch(update))
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0
|
||||
//! `SeaORM` Entity, @generated by sea-orm-codegen 2.0
|
||||
|
||||
pub mod prelude;
|
||||
|
||||
pub mod notes;
|
||||
pub mod users;
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
//! `SeaORM` Entity, @generated by sea-orm-codegen 2.0
|
||||
|
||||
use sea_orm::entity::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel, Serialize, Deserialize)]
|
||||
#[sea_orm(table_name = "notes")]
|
||||
pub struct Model {
|
||||
pub created_at: DateTimeWithTimeZone,
|
||||
pub updated_at: DateTimeWithTimeZone,
|
||||
#[sea_orm(primary_key)]
|
||||
pub id: i64,
|
||||
pub title: Option<String>,
|
||||
#[sea_orm(column_type = "Text", nullable)]
|
||||
pub content: Option<String>,
|
||||
pub user_id: i64,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {
|
||||
#[sea_orm(
|
||||
belongs_to = "super::users::Entity",
|
||||
from = "Column::UserId",
|
||||
to = "super::users::Column::Id",
|
||||
on_update = "Cascade",
|
||||
on_delete = "Cascade"
|
||||
)]
|
||||
Users,
|
||||
}
|
||||
|
||||
impl Related<super::users::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::Users.def()
|
||||
}
|
||||
}
|
||||
@@ -1,2 +1,4 @@
|
||||
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0
|
||||
//! `SeaORM` Entity, @generated by sea-orm-codegen 2.0
|
||||
|
||||
pub use super::notes::Entity as Notes;
|
||||
pub use super::users::Entity as Users;
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0
|
||||
//! `SeaORM` Entity, @generated by sea-orm-codegen 2.0
|
||||
|
||||
use sea_orm::entity::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)]
|
||||
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel, Serialize, Deserialize)]
|
||||
#[sea_orm(table_name = "users")]
|
||||
pub struct Model {
|
||||
pub created_at: DateTimeWithTimeZone,
|
||||
pub updated_at: DateTimeWithTimeZone,
|
||||
#[sea_orm(primary_key)]
|
||||
pub id: i32,
|
||||
pub id: i64,
|
||||
pub pid: Uuid,
|
||||
#[sea_orm(unique)]
|
||||
pub email: String,
|
||||
@@ -27,4 +27,13 @@ pub struct Model {
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {}
|
||||
pub enum Relation {
|
||||
#[sea_orm(has_many = "super::notes::Entity")]
|
||||
Notes,
|
||||
}
|
||||
|
||||
impl Related<super::notes::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::Notes.def()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
pub mod _entities;
|
||||
pub mod users;
|
||||
pub mod notes;
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
use sea_orm::entity::prelude::*;
|
||||
pub use super::_entities::notes::{ActiveModel, Model, Entity};
|
||||
pub type Notes = Entity;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl ActiveModelBehavior for ActiveModel {
|
||||
async fn before_save<C>(self, _db: &C, insert: bool) -> std::result::Result<Self, DbErr>
|
||||
where
|
||||
C: ConnectionTrait,
|
||||
{
|
||||
if !insert && self.updated_at.is_unchanged() {
|
||||
let mut this = self;
|
||||
this.updated_at = sea_orm::ActiveValue::Set(chrono::Utc::now().into());
|
||||
Ok(this)
|
||||
} else {
|
||||
Ok(self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// implement your read-oriented logic here
|
||||
impl Model {}
|
||||
|
||||
// implement your write-oriented logic here
|
||||
impl ActiveModel {}
|
||||
|
||||
// implement your custom finders, selectors oriented logic here
|
||||
impl Entity {}
|
||||
@@ -1 +1,3 @@
|
||||
pub mod auth;
|
||||
|
||||
pub mod note;
|
||||
@@ -0,0 +1,39 @@
|
||||
use loco_rs::prelude::*;
|
||||
|
||||
use crate::models::_entities::notes;
|
||||
|
||||
/// Render a list view of `notes`.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// When there is an issue with rendering the view.
|
||||
pub fn list(v: &impl ViewRenderer, items: &Vec<notes::Model>) -> Result<Response> {
|
||||
format::render().view(v, "note/list.html", data!({"items": items}))
|
||||
}
|
||||
|
||||
/// Render a single `note` view.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// When there is an issue with rendering the view.
|
||||
pub fn show(v: &impl ViewRenderer, item: ¬es::Model) -> Result<Response> {
|
||||
format::render().view(v, "note/show.html", data!({"item": item}))
|
||||
}
|
||||
|
||||
/// Render a `note` create form.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// When there is an issue with rendering the view.
|
||||
pub fn create(v: &impl ViewRenderer) -> Result<Response> {
|
||||
format::render().view(v, "note/create.html", data!({}))
|
||||
}
|
||||
|
||||
/// Render a `note` edit form.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// When there is an issue with rendering the view.
|
||||
pub fn edit(v: &impl ViewRenderer, item: ¬es::Model) -> Result<Response> {
|
||||
format::render().view(v, "note/edit.html", data!({"item": item}))
|
||||
}
|
||||
@@ -1 +1,3 @@
|
||||
mod users;
|
||||
|
||||
mod notes;
|
||||
@@ -0,0 +1,31 @@
|
||||
use notes_service::app::App;
|
||||
use loco_rs::testing::prelude::*;
|
||||
use serial_test::serial;
|
||||
|
||||
macro_rules! configure_insta {
|
||||
($($expr:expr),*) => {
|
||||
let mut settings = insta::Settings::clone_current();
|
||||
settings.set_prepend_module_to_snapshot(false);
|
||||
let _guard = settings.bind_to_scope();
|
||||
};
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn test_model() {
|
||||
configure_insta!();
|
||||
|
||||
let boot = boot_test::<App>().await.unwrap();
|
||||
seed::<App>(&boot.app_context).await.unwrap();
|
||||
|
||||
// query your model, e.g.:
|
||||
//
|
||||
// let item = models::posts::Model::find_by_pid(
|
||||
// &boot.app_context.db,
|
||||
// "11111111-1111-1111-1111-111111111111",
|
||||
// )
|
||||
// .await;
|
||||
|
||||
// snapshot the result:
|
||||
// assert_debug_snapshot!(item);
|
||||
}
|
||||
Reference in New Issue
Block a user