Compare commits

...

59 commits

Author SHA1 Message Date
6557df5e17
feat: added login page 2025-11-23 03:57:35 +03:00
034487e26a
Merge branch 'auth' into front 2025-11-23 03:35:04 +03:00
6485563a95
fix: react imports 2025-11-22 06:37:39 +03:00
f1f7feffaa
feat: /titles page with search and sort functionality. Website header added 2025-11-22 05:45:54 +03:00
31a95fabea
fix: useEffect
All checks were successful
Build and Deploy Go App / build (push) Successful in 17m45s
Build and Deploy Go App / deploy (push) Successful in 3m41s
2025-11-19 11:06:09 +03:00
fd8ecbeaca
Merge branch 'front' into dev
Some checks failed
Build and Deploy Go App / build (push) Failing after 11m25s
Build and Deploy Go App / deploy (push) Has been skipped
2025-11-19 10:55:25 +03:00
397d2bcf70
feat: /titles page implementation with cursor pagination 2025-11-19 10:54:52 +03:00
9c0fada00e fix: delete views column
All checks were successful
Build and Deploy Go App / build (push) Successful in 17m39s
Build and Deploy Go App / deploy (push) Successful in 3m34s
2025-11-19 04:16:23 +03:00
e2ac80610c fix: now gettitles must work
Some checks failed
Build and Deploy Go App / build (push) Has been cancelled
Build and Deploy Go App / deploy (push) Has been cancelled
2025-11-19 04:11:31 +03:00
7e6520c931 Merge branch 'dev' of ssh://meowgit.nekoea.red:22222/nihonium/nyanimedb into dev
Some checks failed
Build and Deploy Go App / build (push) Has been cancelled
Build and Deploy Go App / deploy (push) Has been cancelled
2025-11-19 03:59:45 +03:00
34d9341e75 feat: cursor stub added 2025-11-19 03:58:46 +03:00
fbf3f1d3a2 feat: now use _build to build 2025-11-19 03:57:44 +03:00
2025bb451f refact: openapi splitted into separate files 2025-11-19 03:14:41 +03:00
9ed09500ed
refact: slightly refactored openapi spec 2025-11-19 01:42:40 +03:00
a515769823
Merge branch 'dev-ars' into front 2025-11-19 01:13:19 +03:00
cdfa14cece feat: cursor added 2025-11-19 00:41:54 +03:00
c0be58ba07
feat: use pgxpool in backend
All checks were successful
Build and Deploy Go App / build (push) Successful in 17m56s
Build and Deploy Go App / deploy (push) Successful in 3m42s
2025-11-18 15:39:24 +03:00
a9391c18b9
fix: TitlesPage import path
All checks were successful
Build and Deploy Go App / build (push) Successful in 18m5s
Build and Deploy Go App / deploy (push) Successful in 3m36s
2025-11-18 15:30:11 +03:00
8504746d27
fix: updated package.json
All checks were successful
Build and Deploy Go App / build (push) Successful in 17m52s
Build and Deploy Go App / deploy (push) Successful in 4m19s
2025-11-18 05:39:11 +03:00
ecccc29aa8
fix
Some checks failed
Build and Deploy Go App / build (push) Has been cancelled
Build and Deploy Go App / deploy (push) Has been cancelled
2025-11-18 05:34:42 +03:00
7e41b6b9ce
fix
Some checks failed
Build and Deploy Go App / build (push) Failing after 11m5s
Build and Deploy Go App / deploy (push) Has been skipped
2025-11-18 05:26:01 +03:00
b976c35b8e
feat: titles page
Some checks failed
Build and Deploy Go App / build (push) Failing after 11m8s
Build and Deploy Go App / deploy (push) Has been skipped
2025-11-18 05:15:38 +03:00
6836cfa057 feat: stub for get user titles written
Some checks failed
Build and Deploy Go App / build (push) Has been cancelled
Build and Deploy Go App / deploy (push) Has been cancelled
2025-11-18 05:11:35 +03:00
09d0d1eb4d feat: get user titles described 2025-11-18 04:59:19 +03:00
8deba7afd9 fix
All checks were successful
Build and Deploy Go App / build (push) Successful in 17m41s
Build and Deploy Go App / deploy (push) Successful in 3m34s
2025-11-18 04:19:34 +03:00
8371121130 fix
All checks were successful
Build and Deploy Go App / build (push) Successful in 17m59s
Build and Deploy Go App / deploy (push) Successful in 3m34s
2025-11-18 03:12:16 +03:00
148ae646b1 feat
All checks were successful
Build and Deploy Go App / build (push) Successful in 17m38s
Build and Deploy Go App / deploy (push) Successful in 3m33s
2025-11-17 09:39:26 +03:00
76d28d0170 Merge branch 'dev-ars' into dev
Some checks failed
Build and Deploy Go App / build (push) Has been cancelled
Build and Deploy Go App / deploy (push) Has been cancelled
2025-11-17 09:27:32 +03:00
df45a327e6 fix 2025-11-17 09:26:58 +03:00
abf09e5f5e Merge branch 'dev-ars' of ssh://meowgit.nekoea.red:22222/nihonium/nyanimedb into dev-ars 2025-11-17 03:56:27 +03:00
35a4e173f0 feat: query GetReviewById added 2025-11-17 03:55:42 +03:00
f888ac9b70
review: review notes for titles.go 2025-11-17 02:41:45 +03:00
fe54b61822 Merge branch 'dev-ars' into dev
All checks were successful
Build and Deploy Go App / build (push) Successful in 17m29s
Build and Deploy Go App / deploy (push) Successful in 3m26s
2025-11-16 04:52:52 +03:00
b81cc86beb fix: 2025-11-16 04:52:11 +03:00
29f0a61299 feat: reviews table added 2025-11-16 04:15:33 +03:00
96611825bc Merge branch 'dev-ars' into dev
All checks were successful
Build and Deploy Go App / build (push) Successful in 18m14s
Build and Deploy Go App / deploy (push) Successful in 3m34s
2025-11-16 03:45:06 +03:00
47989ab10d feat: /titles/{id} endpoint implemented 2025-11-16 03:38:51 +03:00
cefbbec1dc feat: wrote query to get one title 2025-11-16 02:43:28 +03:00
13a283ae8d feat: GetTitles now returns all the field needed 2025-11-16 02:38:36 +03:00
d1180a426f feat: new schema for images 2025-11-16 02:14:38 +03:00
e18f4a44c3 feat: more fields for titles and refactored schemas 2025-11-16 01:47:11 +03:00
4949a3c25f refactor: new types 2025-11-15 23:00:40 +03:00
e6dc27fd55 feat: statements for tags added 2025-11-15 19:19:39 +03:00
3cca6ee168 feat: statements for studios table added 2025-11-15 18:56:46 +03:00
2edf96571b feat: field studio_name added to title in openapi 2025-11-15 18:20:27 +03:00
f49fad2307 fix: tmp commeneted method
All checks were successful
Build and Deploy Go App / build (push) Successful in 18m15s
Build and Deploy Go App / deploy (push) Successful in 4m50s
2025-11-15 03:01:38 +03:00
5cc6757900 feat: minor changes to db and new query
Some checks failed
Build and Deploy Go App / build (push) Failing after 5m56s
Build and Deploy Go App / deploy (push) Has been skipped
2025-11-15 02:51:52 +03:00
e8783a0e9d feat: get title func written 2025-11-15 02:51:13 +03:00
ae01eec0fd fix!: some types were changed 2025-11-15 02:50:29 +03:00
d04248ab7a feat 2025-11-15 01:02:30 +03:00
d2450ffc89 feat: titles.go added 2025-11-15 00:52:23 +03:00
c2dc762700 feat: openapi changes 2025-11-15 00:46:47 +03:00
765e75e8bb feat: new responses added 2025-11-15 00:04:43 +03:00
7fed5ed536 feat: get titles added with all components needed 2025-11-14 23:57:34 +03:00
f24edc5dd7 feat: external_services table create 2025-11-14 15:34:48 +03:00
83fee98059 feat: external_ids table is added for binding user sessions in tg and
other services
2025-11-14 15:22:14 +03:00
bac889b627 fix: regexps for mail and nickname were corrected 2025-11-05 17:20:09 +03:00
4ffa7dc93e feat: add new user handler was uncommented 2025-11-05 17:11:43 +03:00
6d538ed154 feat: common code for back functions are now in handlers/common.go 2025-11-01 21:17:42 +03:00
84 changed files with 5401 additions and 934 deletions

View file

@ -0,0 +1,6 @@
package: oapi
generate:
strict-server: true
gin-server: true
models: true
output: api/api.gen.go

436
api/_build/openapi.yaml Normal file
View file

@ -0,0 +1,436 @@
openapi: 3.0.4
info:
title: 'Titles, Users, Reviews, Tags, and Media API'
version: 1.0.0
servers:
- url: /api/v1
paths:
/titles:
get:
summary: Get titles
parameters:
- $ref: '#/components/parameters/cursor'
- $ref: '#/components/parameters/title_sort'
- in: query
name: sort_forward
schema:
type: boolean
default: true
- in: query
name: word
schema:
type: string
- in: query
name: status
schema:
$ref: '#/components/schemas/TitleStatus'
- in: query
name: rating
schema:
type: number
format: double
- in: query
name: release_year
schema:
type: integer
format: int32
- in: query
name: release_season
schema:
$ref: '#/components/schemas/ReleaseSeason'
- in: query
name: limit
schema:
type: integer
format: int32
default: 10
- in: query
name: offset
schema:
type: integer
format: int32
default: 0
- in: query
name: fields
schema:
type: string
default: all
responses:
'200':
description: List of titles with cursor
content:
application/json:
schema:
type: object
properties:
data:
type: array
items:
$ref: '#/components/schemas/Title'
description: List of titles
cursor:
$ref: '#/components/schemas/CursorObj'
required:
- data
- cursor
'204':
description: No titles found
'400':
description: Request params are not correct
'500':
description: Unknown server error
'/titles/{title_id}':
get:
summary: Get title description
parameters:
- in: path
name: title_id
required: true
schema:
type: integer
format: int64
- in: query
name: fields
schema:
type: string
default: all
responses:
'200':
description: Title description
content:
application/json:
schema:
$ref: '#/components/schemas/Title'
'204':
description: No title found
'400':
description: Request params are not correct
'404':
description: Title not found
'500':
description: Unknown server error
'/users/{user_id}':
get:
summary: Get user info
parameters:
- in: path
name: user_id
required: true
schema:
type: string
- in: query
name: fields
schema:
type: string
default: all
responses:
'200':
description: User info
content:
application/json:
schema:
$ref: '#/components/schemas/User'
'400':
description: Request params are not correct
'404':
description: User not found
'500':
description: Unknown server error
'/users/{user_id}/titles/':
get:
summary: Get user titles
parameters:
- $ref: '#/components/parameters/cursor'
- in: path
name: user_id
required: true
schema:
type: string
- in: query
name: word
schema:
type: string
- in: query
name: status
schema:
$ref: '#/components/schemas/TitleStatus'
- in: query
name: watch_status
schema:
$ref: '#/components/schemas/UserTitleStatus'
- in: query
name: rating
schema:
type: number
format: double
- in: query
name: release_year
schema:
type: integer
format: int32
- in: query
name: release_season
schema:
$ref: '#/components/schemas/ReleaseSeason'
- in: query
name: limit
schema:
type: integer
format: int32
default: 10
- in: query
name: fields
schema:
type: string
default: all
responses:
'200':
description: List of user titles
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/UserTitle'
'204':
description: No titles found
'400':
description: Request params are not correct
'500':
description: Unknown server error
components:
parameters:
cursor:
in: query
name: cursor
required: false
schema:
type: string
title_sort:
in: query
name: sort
required: false
schema:
$ref: '#/components/schemas/TitleSort'
schemas:
CursorObj:
type: object
required:
- id
properties:
id:
type: integer
format: int64
param:
type: string
TitleSort:
type: string
description: Title sort order
default: id
enum:
- id
- year
- rating
- views
Image:
type: object
properties:
id:
type: integer
format: int64
storage_type:
type: string
image_path:
type: string
TitleStatus:
type: string
description: Title status
enum:
- finished
- ongoing
- planned
ReleaseSeason:
type: string
description: Title release season
enum:
- winter
- spring
- summer
- fall
UserTitleStatus:
type: string
description: User's title status
enum:
- finished
- planned
- dropped
- in-progress
Review:
type: object
additionalProperties: true
Tag:
type: object
description: 'A localized tag: keys are language codes (ISO 639-1), values are tag names'
additionalProperties:
type: string
example:
en: Shojo
ru: Сёдзё
ja: 少女
Tags:
type: array
description: Array of localized tags
items:
$ref: '#/components/schemas/Tag'
example:
- en: Shojo
ru: Сёдзё
ja: 少女
- en: Shounen
ru: Сёнен
ja: 少年
Studio:
type: object
required:
- id
- name
properties:
id:
type: integer
format: int64
name:
type: string
poster:
$ref: '#/components/schemas/Image'
description:
type: string
Title:
type: object
required:
- id
- title_names
- tags
properties:
id:
type: integer
format: int64
description: Unique title ID (primary key)
example: 1
title_names:
type: object
description: 'Localized titles. Key = language (ISO 639-1), value = list of names'
additionalProperties:
type: array
items:
type: string
example: Attack on Titan
minItems: 1
example:
- Attack on Titan
- AoT
example:
en:
- Attack on Titan
- AoT
ru:
- Атака титанов
- Титаны
ja:
- 進撃の巨人
studio:
$ref: '#/components/schemas/Studio'
tags:
$ref: '#/components/schemas/Tags'
poster:
$ref: '#/components/schemas/Image'
title_status:
$ref: '#/components/schemas/TitleStatus'
rating:
type: number
format: double
rating_count:
type: integer
format: int32
release_year:
type: integer
format: int32
release_season:
$ref: '#/components/schemas/ReleaseSeason'
episodes_aired:
type: integer
format: int32
episodes_all:
type: integer
format: int32
episodes_len:
type: object
additionalProperties:
type: number
format: double
additionalProperties: true
User:
type: object
properties:
id:
type: integer
format: int64
description: Unique user ID (primary key)
example: 1
avatar_id:
type: integer
format: int64
description: ID of the user avatar (references images table)
example: null
mail:
type: string
format: email
description: User email
example: john.doe@example.com
nickname:
type: string
description: Username (alphanumeric + _ or -)
maxLength: 16
example: john_doe_42
disp_name:
type: string
description: Display name
maxLength: 32
example: John Doe
user_desc:
type: string
description: User description
maxLength: 512
example: Just a regular user.
creation_date:
type: string
format: date-time
description: Timestamp when the user was created
example: '2025-10-10T23:45:47.908073Z'
required:
- user_id
- nickname
UserTitle:
type: object
required:
- user_id
- title_id
- status
properties:
user_id:
type: integer
format: int64
title_id:
type: integer
format: int64
status:
$ref: '#/components/schemas/UserTitleStatus'
rate:
type: integer
format: int32
review_id:
type: integer
format: int64
ctime:
type: string
format: date-time
additionalProperties: true

File diff suppressed because it is too large Load diff

View file

@ -1,592 +1,22 @@
openapi: 3.1.1
openapi: 3.0.4
info:
title: Titles, Users, Reviews, Tags, and Media API
version: 1.0.0
servers:
- url: /api/v1
paths:
# /title:
# get:
# summary: Get titles
# parameters:
# - in: query
# name: query
# schema:
# type: string
# - in: query
# name: limit
# schema:
# type: integer
# default: 10
# - in: query
# name: offset
# schema:
# type: integer
# default: 0
# - in: query
# name: fields
# schema:
# type: string
# default: all
# responses:
# '200':
# description: List of titles
# content:
# application/json:
# schema:
# type: array
# items:
# $ref: '#/components/schemas/Title'
# '204':
# description: No titles found
# /title/{title_id}:
# get:
# summary: Get title description
# parameters:
# - in: path
# name: title_id
# required: true
# schema:
# type: string
# - in: query
# name: fields
# schema:
# type: string
# default: all
# responses:
# '200':
# description: Title description
# content:
# application/json:
# schema:
# $ref: '#/components/schemas/Title'
# '404':
# description: Title not found
# patch:
# summary: Update title info
# parameters:
# - in: path
# name: title_id
# required: true
# schema:
# type: string
# requestBody:
# required: true
# content:
# application/json:
# schema:
# $ref: '#/components/schemas/Title'
# responses:
# '200':
# description: Update result
# content:
# application/json:
# schema:
# type: object
# properties:
# success:
# type: boolean
# error:
# type: string
# user_json:
# $ref: '#/components/schemas/User'
# /title/{title_id}/reviews:
# get:
# summary: Get title reviews
# parameters:
# - in: path
# name: title_id
# required: true
# schema:
# type: string
# - in: query
# name: limit
# schema:
# type: integer
# default: 10
# - in: query
# name: offset
# schema:
# type: integer
# default: 0
# responses:
# '200':
# description: List of reviews
# content:
# application/json:
# schema:
# type: array
# items:
# $ref: '#/components/schemas/Review'
# '204':
# description: No reviews found
/titles:
$ref: "./paths/titles.yaml"
/titles/{title_id}:
$ref: "./paths/titles-id.yaml"
/users/{user_id}:
get:
summary: Get user info
parameters:
- in: path
name: user_id
required: true
schema:
type: string
- in: query
name: fields
schema:
type: string
default: all
responses:
'200':
description: User info
content:
application/json:
schema:
$ref: '#/components/schemas/User'
'404':
description: User not found
# patch:
# summary: Update user
# parameters:
# - in: path
# name: user_id
# required: true
# schema:
# type: string
# requestBody:
# required: true
# content:
# application/json:
# schema:
# $ref: '#/components/schemas/User'
# responses:
# '200':
# description: Update result
# content:
# application/json:
# schema:
# type: object
# properties:
# success:
# type: boolean
# error:
# type: string
# delete:
# summary: Delete user
# parameters:
# - in: path
# name: user_id
# required: true
# schema:
# type: string
# responses:
# '200':
# description: Delete result
# content:
# application/json:
# schema:
# type: object
# properties:
# success:
# type: boolean
# error:
# type: string
# /users:
# get:
# summary: Search user
# parameters:
# - in: query
# name: query
# schema:
# type: string
# - in: query
# name: fields
# schema:
# type: string
# responses:
# '200':
# description: List of users
# content:
# application/json:
# schema:
# type: array
# items:
# $ref: '#/components/schemas/User'
# post:
# summary: Add new user
# requestBody:
# required: true
# content:
# application/json:
# schema:
# $ref: '#/components/schemas/User'
# responses:
# '200':
# description: Add result
# content:
# application/json:
# schema:
# type: object
# properties:
# success:
# type: boolean
# error:
# type: string
# user_json:
# $ref: '#/components/schemas/User'
# /users/{user_id}/titles:
# get:
# summary: Get user titles
# parameters:
# - in: path
# name: user_id
# required: true
# schema:
# type: string
# - in: query
# name: query
# schema:
# type: string
# - in: query
# name: limit
# schema:
# type: integer
# default: 10
# - in: query
# name: offset
# schema:
# type: integer
# default: 0
# - in: query
# name: fields
# schema:
# type: string
# default: all
# responses:
# '200':
# description: List of user titles
# content:
# application/json:
# schema:
# type: array
# items:
# $ref: '#/components/schemas/UserTitle'
# '204':
# description: No titles found
# post:
# summary: Add user title
# parameters:
# - in: path
# name: user_id
# required: true
# schema:
# type: string
# requestBody:
# required: true
# content:
# application/json:
# schema:
# type: object
# properties:
# title_id:
# type: string
# status:
# type: string
# responses:
# '200':
# description: Add result
# content:
# application/json:
# schema:
# type: object
# properties:
# success:
# type: boolean
# error:
# type: string
# patch:
# summary: Update user title
# parameters:
# - in: path
# name: user_id
# required: true
# schema:
# type: string
# requestBody:
# required: true
# content:
# application/json:
# schema:
# $ref: '#/components/schemas/UserTitle'
# responses:
# '200':
# description: Update result
# content:
# application/json:
# schema:
# type: object
# properties:
# success:
# type: boolean
# error:
# type: string
# delete:
# summary: Delete user title
# parameters:
# - in: path
# name: user_id
# required: true
# schema:
# type: string
# - in: query
# name: title_id
# schema:
# type: string
# responses:
# '200':
# description: Delete result
# content:
# application/json:
# schema:
# type: object
# properties:
# success:
# type: boolean
# error:
# type: string
# /users/{user_id}/reviews:
# get:
# summary: Get user reviews
# parameters:
# - in: path
# name: user_id
# required: true
# schema:
# type: string
# - in: query
# name: limit
# schema:
# type: integer
# default: 10
# - in: query
# name: offset
# schema:
# type: integer
# default: 0
# responses:
# '200':
# description: List of reviews
# content:
# application/json:
# schema:
# type: array
# items:
# $ref: '#/components/schemas/Review'
# /reviews:
# post:
# summary: Add review
# requestBody:
# required: true
# content:
# application/json:
# schema:
# $ref: '#/components/schemas/Review'
# responses:
# '200':
# description: Add result
# content:
# application/json:
# schema:
# type: object
# properties:
# success:
# type: boolean
# error:
# type: string
# /reviews/{review_id}:
# patch:
# summary: Update review
# parameters:
# - in: path
# name: review_id
# required: true
# schema:
# type: string
# requestBody:
# required: true
# content:
# application/json:
# schema:
# $ref: '#/components/schemas/Review'
# responses:
# '200':
# description: Update result
# content:
# application/json:
# schema:
# type: object
# properties:
# success:
# type: boolean
# error:
# type: string
# delete:
# summary: Delete review
# parameters:
# - in: path
# name: review_id
# required: true
# schema:
# type: string
# responses:
# '200':
# description: Delete result
# content:
# application/json:
# schema:
# type: object
# properties:
# success:
# type: boolean
# error:
# type: string
# /tags:
# get:
# summary: Get tags
# parameters:
# - in: query
# name: limit
# schema:
# type: integer
# default: 10
# - in: query
# name: offset
# schema:
# type: integer
# default: 0
# - in: query
# name: fields
# schema:
# type: string
# responses:
# '200':
# description: List of tags
# content:
# application/json:
# schema:
# type: array
# items:
# $ref: '#/components/schemas/Tag'
# /media:
# post:
# summary: Upload image
# responses:
# '200':
# description: Upload result
# content:
# application/json:
# schema:
# type: object
# properties:
# success:
# type: boolean
# error:
# type: string
# image_id:
# type: string
# get:
# summary: Get image path
# parameters:
# - in: query
# name: image_id
# required: true
# schema:
# type: string
# responses:
# '200':
# description: Image path
# content:
# application/json:
# schema:
# type: object
# properties:
# success:
# type: boolean
# error:
# type: string
# image_path:
# type: string
$ref: "./paths/users-id.yaml"
/users/{user_id}/titles/:
$ref: "./paths/users-id-titles.yaml"
components:
parameters:
$ref: "./parameters/_index.yaml"
schemas:
Title:
type: object
additionalProperties: true
User:
type: object
properties:
id:
type: integer
format: int64
description: Unique user ID (primary key)
example: 1
avatar_id:
type: integer
format: int64
description: ID of the user avatar (references images table)
nullable: true
example: null
mail:
type: string
format: email
description: User email
example: "john.doe@example.com"
nickname:
type: string
description: Username (alphanumeric + _ or -)
maxLength: 16
example: "john_doe_42"
disp_name:
type: string
description: Display name
maxLength: 32
example: "John Doe"
user_desc:
type: string
description: User description
maxLength: 512
example: "Just a regular user."
creation_date:
type: string
format: date-time
description: Timestamp when the user was created
example: "2025-10-10T23:45:47.908073Z"
required:
- user_id
- nickname
- creation_date
UserTitle:
type: object
additionalProperties: true
Review:
type: object
additionalProperties: true
Tag:
type: object
additionalProperties: true
$ref: "./schemas/_index.yaml"

View file

@ -0,0 +1,4 @@
cursor:
$ref: "./cursor.yaml"
title_sort:
$ref: "./title_sort.yaml"

View file

@ -0,0 +1,5 @@
in: query
name: cursor
required: false
schema:
type: string

View file

@ -0,0 +1,5 @@
in: query
name: sort
required: false
schema:
$ref: '../schemas/TitleSort.yaml'

29
api/paths/titles-id.yaml Normal file
View file

@ -0,0 +1,29 @@
get:
summary: Get title description
parameters:
- in: path
name: title_id
required: true
schema:
type: integer
format: int64
- in: query
name: fields
schema:
type: string
default: all
responses:
'200':
description: Title description
content:
application/json:
schema:
$ref: "../schemas/Title.yaml"
'404':
description: Title not found
'400':
description: Request params are not correct
'500':
description: Unknown server error
'204':
description: No title found

73
api/paths/titles.yaml Normal file
View file

@ -0,0 +1,73 @@
get:
summary: Get titles
parameters:
- $ref: "../parameters/cursor.yaml"
- $ref: "../parameters/title_sort.yaml"
- in: query
name: sort_forward
schema:
type: boolean
default: true
- in: query
name: word
schema:
type: string
- in: query
name: status
schema:
$ref: '../schemas/enums/TitleStatus.yaml'
- in: query
name: rating
schema:
type: number
format: double
- in: query
name: release_year
schema:
type: integer
format: int32
- in: query
name: release_season
schema:
$ref: '../schemas/enums/ReleaseSeason.yaml'
- in: query
name: limit
schema:
type: integer
format: int32
default: 10
- in: query
name: offset
schema:
type: integer
format: int32
default: 0
- in: query
name: fields
schema:
type: string
default: all
responses:
'200':
description: List of titles with cursor
content:
application/json:
schema:
type: object
properties:
data:
type: array
items:
$ref: '../schemas/Title.yaml'
description: List of titles
cursor:
$ref: '../schemas/CursorObj.yaml'
required:
- data
- cursor
'204':
description: No titles found
'400':
description: Request params are not correct
'500':
description: Unknown server error

View file

@ -0,0 +1,61 @@
get:
summary: Get user titles
parameters:
- $ref: '../parameters/cursor.yaml'
- in: path
name: user_id
required: true
schema:
type: string
- in: query
name: word
schema:
type: string
- in: query
name: status
schema:
$ref: '../schemas/enums/TitleStatus.yaml'
- in: query
name: watch_status
schema:
$ref: '../schemas/enums/UserTitleStatus.yaml'
- in: query
name: rating
schema:
type: number
format: double
- in: query
name: release_year
schema:
type: integer
format: int32
- in: query
name: release_season
schema:
$ref: '../schemas/enums/ReleaseSeason.yaml'
- in: query
name: limit
schema:
type: integer
format: int32
default: 10
- in: query
name: fields
schema:
type: string
default: all
responses:
'200':
description: List of user titles
content:
application/json:
schema:
type: array
items:
$ref: '../schemas/UserTitle.yaml'
'204':
description: No titles found
'400':
description: Request params are not correct
'500':
description: Unknown server error

26
api/paths/users-id.yaml Normal file
View file

@ -0,0 +1,26 @@
get:
summary: Get user info
parameters:
- in: path
name: user_id
required: true
schema:
type: string
- in: query
name: fields
schema:
type: string
default: all
responses:
'200':
description: User info
content:
application/json:
schema:
$ref: '../schemas/User.yaml'
'404':
description: User not found
'400':
description: Request params are not correct
'500':
description: Unknown server error

View file

@ -0,0 +1,9 @@
type: object
required:
- id
properties:
id:
type: integer
format: int64
param:
type: string

9
api/schemas/Image.yaml Normal file
View file

@ -0,0 +1,9 @@
type: object
properties:
id:
type: integer
format: int64
storage_type:
type: string
image_path:
type: string

2
api/schemas/Review.yaml Normal file
View file

@ -0,0 +1,2 @@
type: object
additionalProperties: true

14
api/schemas/Studio.yaml Normal file
View file

@ -0,0 +1,14 @@
type: object
required:
- id
- name
properties:
id:
type: integer
format: int64
name:
type: string
poster:
$ref: ./Image.yaml
description:
type: string

8
api/schemas/Tag.yaml Normal file
View file

@ -0,0 +1,8 @@
type: object
description: 'A localized tag: keys are language codes (ISO 639-1), values are tag names'
additionalProperties:
type: string
example:
en: Shojo
ru: Сёдзё
ja: 少女

11
api/schemas/Tags.yaml Normal file
View file

@ -0,0 +1,11 @@
type: array
description: Array of localized tags
items:
$ref: ./Tag.yaml
example:
- en: Shojo
ru: Сёдзё
ja: 少女
- en: Shounen
ru: Сёнен
ja: 少年

63
api/schemas/Title.yaml Normal file
View file

@ -0,0 +1,63 @@
type: object
required:
- id
- title_names
- tags
properties:
id:
type: integer
format: int64
description: Unique title ID (primary key)
example: 1
title_names:
type: object
description: Localized titles. Key = language (ISO 639-1), value = list of names
additionalProperties:
type: array
items:
type: string
example: Attack on Titan
minItems: 1
example:
- Attack on Titan
- AoT
example:
en:
- Attack on Titan
- AoT
ru:
- Атака титанов
- Титаны
ja:
- 進撃の巨人
studio:
$ref: ./Studio.yaml
tags:
$ref: ./Tags.yaml
poster:
$ref: ./Image.yaml
title_status:
$ref: ./enums/TitleStatus.yaml
rating:
type: number
format: double
rating_count:
type: integer
format: int32
release_year:
type: integer
format: int32
release_season:
$ref: ./enums/ReleaseSeason.yaml
episodes_aired:
type: integer
format: int32
episodes_all:
type: integer
format: int32
episodes_len:
type: object
additionalProperties:
type: number
format: double
additionalProperties: true

View file

@ -0,0 +1,8 @@
type: string
description: Title sort order
default: id
enum:
- id
- year
- rating
- views

40
api/schemas/User.yaml Normal file
View file

@ -0,0 +1,40 @@
type: object
properties:
id:
type: integer
format: int64
description: Unique user ID (primary key)
example: 1
avatar_id:
type: integer
format: int64
description: ID of the user avatar (references images table)
example: null
mail:
type: string
format: email
description: User email
example: john.doe@example.com
nickname:
type: string
description: Username (alphanumeric + _ or -)
maxLength: 16
example: john_doe_42
disp_name:
type: string
description: Display name
maxLength: 32
example: John Doe
user_desc:
type: string
description: User description
maxLength: 512
example: Just a regular user.
creation_date:
type: string
format: date-time
description: Timestamp when the user was created
example: '2025-10-10T23:45:47.908073Z'
required:
- user_id
- nickname

View file

@ -0,0 +1,24 @@
type: object
required:
- user_id
- title_id
- status
properties:
user_id:
type: integer
format: int64
title_id:
type: integer
format: int64
status:
$ref: ./enums/UserTitleStatus.yaml
rate:
type: integer
format: int32
review_id:
type: integer
format: int64
ctime:
type: string
format: date-time
additionalProperties: true

26
api/schemas/_index.yaml Normal file
View file

@ -0,0 +1,26 @@
CursorObj:
$ref: ./CursorObj.yaml
TitleSort:
$ref: "./TitleSort.yaml"
Image:
$ref: "./Image.yaml"
TitleStatus:
$ref: "./enums/TitleStatus.yaml"
ReleaseSeason:
$ref: "./enums/ReleaseSeason.yaml"
UserTitleStatus:
$ref: "./enums/UserTitleStatus.yaml"
Review:
$ref: "./Review.yaml"
Tag:
$ref: "./Tag.yaml"
Tags:
$ref: "./Tags.yaml"
Studio:
$ref: "./Studio.yaml"
Title:
$ref: "./Title.yaml"
User:
$ref: "./User.yaml"
UserTitle:
$ref: "./UserTitle.yaml"

View file

@ -0,0 +1,7 @@
type: string
description: Title release season
enum:
- winter
- spring
- summer
- fall

View file

@ -0,0 +1,6 @@
type: string
description: Title status
enum:
- finished
- ongoing
- planned

View file

@ -0,0 +1,7 @@
type: string
description: User's title status
enum:
- finished
- planned
- dropped
- in-progress

View file

@ -3,6 +3,9 @@ info:
title: Auth Service
version: 1.0.0
servers:
- url: /auth
paths:
/auth/sign-up:
post:

2
go.mod
View file

@ -9,6 +9,7 @@ require (
github.com/jackc/pgx/v5 v5.7.6
github.com/oapi-codegen/runtime v1.1.2
github.com/pelletier/go-toml/v2 v2.2.4
github.com/sirupsen/logrus v1.9.3
)
require (
@ -26,6 +27,7 @@ require (
github.com/google/uuid v1.5.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect

3
go.sum
View file

@ -70,6 +70,8 @@ github.com/quic-go/qpack v0.5.1 h1:giqksBPnT/HDtZ6VhtFKgoLOWmlyo9Ei6u9PqzIMbhI=
github.com/quic-go/qpack v0.5.1/go.mod h1:+PC4XFrEskIVkcLzpEkbLqq1uCoxPhQuvK5rH1ZgaEg=
github.com/quic-go/quic-go v0.54.0 h1:6s1YB9QotYI6Ospeiguknbp2Znb/jZYjZLRXn9kMQBg=
github.com/quic-go/quic-go v0.54.0/go.mod h1:e68ZEaCdyviluZmy44P6Iey98v/Wfz6HCjQEm+l8zTY=
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/spkg/bom v0.0.0-20160624110644-59b7046e48ad/go.mod h1:qLr4V1qq6nMqFKkMo8ZTx3f+BZEkzsRUY10Xsm2mwU0=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
@ -97,6 +99,7 @@ golang.org/x/net v0.42.0 h1:jzkYrhi3YQWD6MLBJcsklgQsoAcw89EcZbJw8Z614hs=
golang.org/x/net v0.42.0/go.mod h1:FF1RA5d3u7nAYA4z2TkclSCKh68eSXtiFwcWQpPXdt8=
golang.org/x/sync v0.16.0 h1:ycBJEhp9p4vXvUZNszeOq0kGTPghopOL8q0fq3vstxw=
golang.org/x/sync v0.16.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI=
golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=

View file

@ -0,0 +1,19 @@
package handlers
import (
sqlc "nyanimedb/sql"
"strconv"
)
type Server struct {
db *sqlc.Queries
}
func NewServer(db *sqlc.Queries) Server {
return Server{db: db}
}
func parseInt64(s string) (int32, error) {
i, err := strconv.ParseInt(s, 10, 64)
return int32(i), err
}

View file

@ -0,0 +1,266 @@
package handlers
import (
"context"
"encoding/json"
"fmt"
oapi "nyanimedb/api"
sqlc "nyanimedb/sql"
"github.com/jackc/pgx/v5"
log "github.com/sirupsen/logrus"
)
func Word2Sqlc(s *string) *string {
if s == nil || *s == "" {
return nil
}
return s
}
func TitleStatus2Sqlc(s *oapi.TitleStatus) (*sqlc.TitleStatusT, error) {
if s == nil {
return nil, nil
}
var t sqlc.TitleStatusT
switch *s {
case oapi.TitleStatusFinished:
t = sqlc.TitleStatusTFinished
case oapi.TitleStatusOngoing:
t = sqlc.TitleStatusTOngoing
case oapi.TitleStatusPlanned:
t = sqlc.TitleStatusTPlanned
default:
return nil, fmt.Errorf("unexpected tittle status: %s", *s)
}
return &t, nil
}
func ReleaseSeason2sqlc(s *oapi.ReleaseSeason) (*sqlc.ReleaseSeasonT, error) {
if s == nil {
return nil, nil
}
var t sqlc.ReleaseSeasonT
switch *s {
case oapi.Winter:
t = sqlc.ReleaseSeasonTWinter
case oapi.Spring:
t = sqlc.ReleaseSeasonTSpring
case oapi.Summer:
t = sqlc.ReleaseSeasonTSummer
case oapi.Fall:
t = sqlc.ReleaseSeasonTFall
default:
return nil, fmt.Errorf("unexpected release season: %s", *s)
}
return &t, nil
}
func (s Server) GetTagsByTitleId(ctx context.Context, id int64) (oapi.Tags, error) {
sqlc_title_tags, err := s.db.GetTitleTags(ctx, id)
if err != nil {
if err == pgx.ErrNoRows {
return nil, nil
}
return nil, fmt.Errorf("query GetTitleTags: %v", err)
}
oapi_tag_names := make(oapi.Tags, 1)
for _, title_tag := range sqlc_title_tags {
oapi_tag_name := make(map[string]string, 1)
err = json.Unmarshal(title_tag, &oapi_tag_name)
if err != nil {
return nil, fmt.Errorf("unmarshalling title_tag: %v", err)
}
oapi_tag_names = append(oapi_tag_names, oapi_tag_name)
}
return oapi_tag_names, nil
}
func (s Server) GetImage(ctx context.Context, id int64) (*oapi.Image, error) {
var oapi_image oapi.Image
sqlc_image, err := s.db.GetImageByID(ctx, id)
if err != nil {
if err == pgx.ErrNoRows {
return nil, nil //todo: error reference in db
}
return &oapi_image, fmt.Errorf("query GetImageByID: %v", err)
}
//can cast and dont use brain cause all this fields required in image table
oapi_image.Id = &sqlc_image.ID
oapi_image.ImagePath = &sqlc_image.ImagePath
storageTypeStr := string(sqlc_image.StorageType)
oapi_image.StorageType = &storageTypeStr
return &oapi_image, nil
}
func (s Server) GetStudio(ctx context.Context, id int64) (*oapi.Studio, error) {
var oapi_studio oapi.Studio
sqlc_studio, err := s.db.GetStudioByID(ctx, id)
if err != nil {
if err == pgx.ErrNoRows {
return nil, nil
}
return &oapi_studio, fmt.Errorf("query GetStudioByID: %v", err)
}
oapi_studio.Id = sqlc_studio.ID
oapi_studio.Name = sqlc_studio.StudioName
oapi_studio.Description = sqlc_studio.StudioDesc
if sqlc_studio.IllustID == nil {
return &oapi_studio, nil
}
oapi_illust, err := s.GetImage(ctx, *sqlc_studio.IllustID)
if err != nil {
return &oapi_studio, fmt.Errorf("GetImage: %v", err)
}
if oapi_illust != nil {
oapi_studio.Poster = oapi_illust
}
return &oapi_studio, nil
}
func (s Server) mapTitle(ctx context.Context, title sqlc.Title) (oapi.Title, error) {
var oapi_title oapi.Title
title_names := make(map[string][]string, 1)
err := json.Unmarshal(title.TitleNames, &title_names)
if err != nil {
return oapi_title, fmt.Errorf("unmarshal TitleNames: %v", err)
}
episodes_lens := make(map[string]float64, 1)
err = json.Unmarshal(title.EpisodesLen, &episodes_lens)
if err != nil {
return oapi_title, fmt.Errorf("unmarshal EpisodesLen: %v", err)
}
oapi_tag_names, err := s.GetTagsByTitleId(ctx, title.ID)
if err != nil {
return oapi_title, fmt.Errorf("GetTagsByTitleId: %v", err)
}
if oapi_tag_names != nil {
oapi_title.Tags = oapi_tag_names
}
if title.PosterID != nil {
oapi_image, err := s.GetImage(ctx, *title.PosterID)
if err != nil {
return oapi_title, fmt.Errorf("GetImage: %v", err)
}
if oapi_image != nil {
oapi_title.Poster = oapi_image
}
}
oapi_studio, err := s.GetStudio(ctx, title.StudioID)
if err != nil {
return oapi_title, fmt.Errorf("GetStudio: %v", err)
}
if oapi_studio != nil {
oapi_title.Studio = oapi_studio
}
if title.ReleaseSeason != nil {
rs := oapi.ReleaseSeason(*title.ReleaseSeason)
oapi_title.ReleaseSeason = &rs
} else {
oapi_title.ReleaseSeason = nil
}
ts := oapi.TitleStatus(title.TitleStatus)
oapi_title.TitleStatus = &ts
oapi_title.Id = title.ID
oapi_title.Rating = title.Rating
oapi_title.RatingCount = title.RatingCount
oapi_title.ReleaseYear = title.ReleaseYear
oapi_title.TitleNames = title_names
oapi_title.EpisodesAired = title.EpisodesAired
oapi_title.EpisodesAll = title.EpisodesAll
oapi_title.EpisodesLen = &episodes_lens
return oapi_title, nil
}
func (s Server) GetTitlesTitleId(ctx context.Context, request oapi.GetTitlesTitleIdRequestObject) (oapi.GetTitlesTitleIdResponseObject, error) {
var oapi_title oapi.Title
sqlc_title, err := s.db.GetTitleByID(ctx, request.TitleId)
if err != nil {
if err == pgx.ErrNoRows {
return oapi.GetTitlesTitleId204Response{}, nil
}
log.Errorf("%v", err)
return oapi.GetTitlesTitleId500Response{}, nil
}
oapi_title, err = s.mapTitle(ctx, sqlc_title)
if err != nil {
log.Errorf("%v", err)
return oapi.GetTitlesTitleId500Response{}, nil
}
return oapi.GetTitlesTitleId200JSONResponse(oapi_title), nil
}
func (s Server) GetTitles(ctx context.Context, request oapi.GetTitlesRequestObject) (oapi.GetTitlesResponseObject, error) {
opai_titles := make([]oapi.Title, 0)
cursor := oapi.CursorObj{
Id: 1,
}
word := Word2Sqlc(request.Params.Word)
status, err := TitleStatus2Sqlc(request.Params.Status)
if err != nil {
log.Errorf("%v", err)
return oapi.GetTitles400Response{}, err
}
season, err := ReleaseSeason2sqlc(request.Params.ReleaseSeason)
if err != nil {
log.Errorf("%v", err)
return oapi.GetTitles400Response{}, err
}
// param = nil means it will not be used
titles, err := s.db.SearchTitles(ctx, sqlc.SearchTitlesParams{
Word: word,
Status: status,
Rating: request.Params.Rating,
ReleaseYear: request.Params.ReleaseYear,
ReleaseSeason: season,
Forward: true,
SortBy: "id",
Limit: request.Params.Limit,
})
if err != nil {
log.Errorf("%v", err)
return oapi.GetTitles500Response{}, nil
}
if len(titles) == 0 {
return oapi.GetTitles204Response{}, nil
}
for _, title := range titles {
t, err := s.mapTitle(ctx, title)
if err != nil {
log.Errorf("%v", err)
return oapi.GetTitles500Response{}, nil
}
opai_titles = append(opai_titles, t)
}
return oapi.GetTitles200JSONResponse{Cursor: cursor, Data: opai_titles}, nil
}

View file

@ -4,29 +4,29 @@ import (
"context"
oapi "nyanimedb/api"
sqlc "nyanimedb/sql"
"strconv"
"time"
"github.com/jackc/pgx/v5"
"github.com/oapi-codegen/runtime/types"
)
type Server struct {
db *sqlc.Queries
}
// type Server struct {
// db *sqlc.Queries
// }
func NewServer(db *sqlc.Queries) Server {
return Server{db: db}
}
// func NewServer(db *sqlc.Queries) Server {
// return Server{db: db}
// }
func parseInt64(s string) (int32, error) {
i, err := strconv.ParseInt(s, 10, 64)
return int32(i), err
}
// func parseInt64(s string) (int32, error) {
// i, err := strconv.ParseInt(s, 10, 64)
// return int32(i), err
// }
func mapUser(u sqlc.GetUserByIDRow) oapi.User {
return oapi.User{
AvatarId: u.AvatarID,
CreationDate: u.CreationDate,
CreationDate: &u.CreationDate,
DispName: u.DispName,
Id: &u.ID,
Mail: (*types.Email)(u.Mail),
@ -49,3 +49,35 @@ func (s Server) GetUsersUserId(ctx context.Context, req oapi.GetUsersUserIdReque
}
return oapi.GetUsersUserId200JSONResponse(mapUser(user)), nil
}
func (s Server) GetUsersUserIdTitles(ctx context.Context, request oapi.GetUsersUserIdTitlesRequestObject) (oapi.GetUsersUserIdTitlesResponseObject, error) {
var rate int32 = 9
var review_id int64 = 3
time := time.Date(2025, 1, 15, 10, 30, 0, 0, time.UTC)
var userTitles = []oapi.UserTitle{
{
UserId: 101,
TitleId: 2001,
Status: oapi.UserTitleStatusFinished,
Rate: &rate,
Ctime: &time,
},
{
UserId: 102,
TitleId: 2002,
Status: oapi.UserTitleStatusInProgress,
ReviewId: &review_id,
Ctime: &time,
},
{
UserId: 103,
TitleId: 2003,
Status: oapi.UserTitleStatusDropped,
Ctime: &time,
},
}
return oapi.GetUsersUserIdTitles200JSONResponse(userTitles), nil
}

View file

@ -13,7 +13,7 @@ import (
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/pelletier/go-toml/v2"
)
@ -31,17 +31,17 @@ func main() {
// log.Fatalf("Failed to init config: %v\n", err)
// }
conn, err := pgx.Connect(context.Background(), os.Getenv("DATABASE_URL"))
pool, err := pgxpool.New(context.Background(), os.Getenv("DATABASE_URL"))
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to connect to database: %v\n", err)
os.Exit(1)
}
defer conn.Close(context.Background())
defer pool.Close()
r := gin.Default()
queries := sqlc.New(conn)
queries := sqlc.New(pool)
server := handlers.NewServer(queries)
// r.LoadHTMLGlob("templates/*")

View file

@ -1,7 +1,7 @@
-- name: GetImageByID :one
SELECT id, storage_type, image_path
FROM images
WHERE id = $1;
WHERE id = sqlc.arg('illust_id')::bigint;
-- name: CreateImage :one
INSERT INTO images (storage_type, image_path)
@ -13,6 +13,40 @@ SELECT id, avatar_id, mail, nickname, disp_name, user_desc, creation_date
FROM users
WHERE id = $1;
-- name: GetStudioByID :one
SELECT *
FROM studios
WHERE id = sqlc.arg('studio_id')::bigint;
-- name: InsertStudio :one
INSERT INTO studios (studio_name, illust_id, studio_desc)
VALUES (
sqlc.arg('studio_name')::text,
sqlc.narg('illust_id')::bigint,
sqlc.narg('studio_desc')::text)
RETURNING id, studio_name, illust_id, studio_desc;
-- name: GetTitleTags :many
SELECT
tag_names
FROM tags as g
JOIN title_tags as t ON(t.tag_id = g.id)
WHERE t.title_id = sqlc.arg('title_id')::bigint;
-- name: InsertTitleTags :one
INSERT INTO title_tags (title_id, tag_id)
VALUES (
sqlc.arg('title_id')::bigint,
sqlc.arg('tag_id')::bigint)
RETURNING title_id, tag_id;
-- name: InsertTag :one
INSERT INTO tags (tag_names)
VALUES (
sqlc.arg('tag_names')::jsonb)
RETURNING id, tag_names;
-- -- name: ListUsers :many
-- SELECT user_id, avatar_id, passhash, mail, nickname, disp_name, user_desc, creation_date
-- FROM users
@ -38,12 +72,100 @@ WHERE id = $1;
-- DELETE FROM users
-- WHERE user_id = $1;
-- -- name: GetTitleByID :one
-- SELECT title_id, title_names, studio_id, poster_id, signal_ids,
-- title_status, rating, rating_count, release_year, release_season,
-- season, episodes_aired, episodes_all, episodes_len
-- FROM titles
-- WHERE title_id = $1;
-- name: GetTitleByID :one
SELECT *
FROM titles
WHERE id = sqlc.arg('title_id')::bigint;
-- name: SearchTitles :many
SELECT
*
FROM titles
WHERE
CASE
WHEN sqlc.narg('word')::text IS NOT NULL THEN
(
SELECT bool_and(
EXISTS (
SELECT 1
FROM jsonb_each_text(title_names) AS t(key, val)
WHERE val ILIKE pattern
)
)
FROM unnest(
ARRAY(
SELECT '%' || trim(w) || '%'
FROM unnest(string_to_array(sqlc.narg('word')::text, ' ')) AS w
WHERE trim(w) <> ''
)
) AS pattern
)
ELSE true
END
AND (sqlc.narg('status')::title_status_t IS NULL OR title_status = sqlc.narg('status')::title_status_t)
AND (sqlc.narg('rating')::float IS NULL OR rating >= sqlc.narg('rating')::float)
AND (sqlc.narg('release_year')::int IS NULL OR release_year = sqlc.narg('release_year')::int)
AND (sqlc.narg('release_season')::release_season_t IS NULL OR release_season = sqlc.narg('release_season')::release_season_t)
ORDER BY
-- Основной ключ: выбранное поле
CASE
WHEN sqlc.arg(forward)::boolean AND sqlc.arg(sort_by)::text = 'id' THEN id
WHEN sqlc.arg(forward)::boolean AND sqlc.arg(sort_by)::text = 'year' THEN release_year
WHEN sqlc.arg(forward)::boolean AND sqlc.arg(sort_by)::text = 'rating' THEN rating
-- WHEN sqlc.arg(forward)::boolean AND sqlc.arg(sort_by)::text = 'views' THEN views
END ASC,
CASE
WHEN NOT sqlc.arg(forward)::boolean AND sqlc.arg(sort_by)::text = 'id' THEN id
WHEN NOT sqlc.arg(forward)::boolean AND sqlc.arg(sort_by)::text = 'year' THEN release_year
WHEN NOT sqlc.arg(forward)::boolean AND sqlc.arg(sort_by)::text = 'rating' THEN rating
-- WHEN NOT sqlc.arg(forward)::boolean AND sqlc.arg(sort_by)::text = 'views' THEN views
END DESC,
-- Вторичный ключ: id — только если НЕ сортируем по id
CASE
WHEN sqlc.arg(sort_by)::text != 'id' AND sqlc.arg(forward)::boolean THEN id
END ASC,
CASE
WHEN sqlc.arg(sort_by)::text != 'id' AND NOT sqlc.arg(forward)::boolean THEN id
END DESC
LIMIT COALESCE(sqlc.narg('limit')::int, 100); -- 100 is default limit
-- OFFSET sqlc.narg('offset')::int;
-- name: SearchUserTitles :many
SELECT
*
FROM usertitles as u
JOIN titles as t ON (u.title_id = t.id)
WHERE
CASE
WHEN sqlc.narg('word')::text IS NOT NULL THEN
(
SELECT bool_and(
EXISTS (
SELECT 1
FROM jsonb_each_text(t.title_names) AS t(key, val)
WHERE val ILIKE pattern
)
)
FROM unnest(
ARRAY(
SELECT '%' || trim(w) || '%'
FROM unnest(string_to_array(sqlc.narg('word')::text, ' ')) AS w
WHERE trim(w) <> ''
)
) AS pattern
)
ELSE true
END
AND (sqlc.narg('status')::title_status_t IS NULL OR t.title_status = sqlc.narg('status')::title_status_t)
AND (sqlc.narg('rating')::float IS NULL OR t.rating >= sqlc.narg('rating')::float)
AND (sqlc.narg('release_year')::int IS NULL OR t.release_year = sqlc.narg('release_year')::int)
AND (sqlc.narg('release_season')::release_season_t IS NULL OR t.release_season = sqlc.narg('release_season')::release_season_t)
AND (sqlc.narg('usertitle_status')::usertitle_status_t IS NULL OR u.usertitle_status = sqlc.narg('usertitle_status')::usertitle_status_t)
LIMIT COALESCE(sqlc.narg('limit')::int, 100); -- 100 is default limit
-- -- name: ListTitles :many
-- SELECT title_id, title_names, studio_id, poster_id, signal_ids,
@ -69,10 +191,10 @@ WHERE id = $1;
-- WHERE title_id = sqlc.arg('title_id')
-- RETURNING *;
-- -- name: GetReviewByID :one
-- SELECT review_id, user_id, title_id, image_ids, review_text, creation_date
-- FROM reviews
-- WHERE review_id = $1;
-- name: GetReviewByID :one
SELECT *
FROM reviews
WHERE review_id = sqlc.arg('review_id')::bigint;
-- -- name: CreateReview :one
-- INSERT INTO reviews (user_id, title_id, image_ids, review_text, creation_date)
@ -91,7 +213,7 @@ WHERE id = $1;
-- DELETE FROM reviews
-- WHERE review_id = $1;
-- -- name: ListReviewsByTitle :many
-- name: ListReviewsByTitle :many
-- SELECT review_id, user_id, title_id, image_ids, review_text, creation_date
-- FROM reviews
-- WHERE title_id = $1

File diff suppressed because it is too large Load diff

View file

@ -10,10 +10,14 @@
"preview": "vite preview"
},
"dependencies": {
"@headlessui/react": "^2.2.9",
"@heroicons/react": "^2.2.0",
"@tailwindcss/vite": "^4.1.17",
"axios": "^1.12.2",
"react": "^19.1.1",
"react-dom": "^19.1.1",
"react-router-dom": "^7.9.4"
"react-router-dom": "^7.9.4",
"tailwindcss": "^4.1.17"
},
"devDependencies": {
"@eslint/js": "^9.36.0",
@ -29,5 +33,8 @@
"typescript": "~5.9.3",
"typescript-eslint": "^8.45.0",
"vite": "^7.1.7"
},
"engines": {
"node": "20.x"
}
}

View file

@ -1,42 +0,0 @@
#root {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: filter 300ms;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.react:hover {
filter: drop-shadow(0 0 2em #61dafbaa);
}
@keyframes logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
@media (prefers-reduced-motion: no-preference) {
a:nth-of-type(2) .logo {
animation: logo-spin infinite 20s linear;
}
}
.card {
padding: 2em;
}
.read-the-docs {
color: #888;
}

View file

@ -1,12 +1,20 @@
import React from "react";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import UserPage from "./components/UserPage/UserPage";
import UserPage from "./pages/UserPage/UserPage";
import TitlesPage from "./pages/TitlesPage/TitlesPage";
import { LoginPage } from "./pages/LoginPage/LoginPage";
import { Header } from "./components/Header/Header";
const App: React.FC = () => {
const username = "nihonium";
return (
<Router>
<Header username={username} />
<Routes>
<Route path="/login" element={<LoginPage />} /> {/* <-- маршрут для логина */}
<Route path="/signup" element={<LoginPage />} /> {/* <-- можно использовать тот же компонент для регистрации */}
<Route path="/users/:id" element={<UserPage />} />
<Route path="/titles" element={<TitlesPage />} />
</Routes>
</Router>
);

View file

@ -20,7 +20,7 @@ export type OpenAPIConfig = {
};
export const OpenAPI: OpenAPIConfig = {
BASE: '/api/v1',
BASE: 'http://10.1.0.65:8081/api/v1',
VERSION: '1.0.0',
WITH_CREDENTIALS: false,
CREDENTIALS: 'include',

View file

@ -7,10 +7,20 @@ export { CancelablePromise, CancelError } from './core/CancelablePromise';
export { OpenAPI } from './core/OpenAPI';
export type { OpenAPIConfig } from './core/OpenAPI';
export type { cursor } from './models/cursor';
export type { CursorObj } from './models/CursorObj';
export type { Image } from './models/Image';
export type { ReleaseSeason } from './models/ReleaseSeason';
export type { Review } from './models/Review';
export type { Studio } from './models/Studio';
export type { Tag } from './models/Tag';
export type { Tags } from './models/Tags';
export type { Title } from './models/Title';
export type { title_sort } from './models/title_sort';
export type { TitleSort } from './models/TitleSort';
export type { TitleStatus } from './models/TitleStatus';
export type { User } from './models/User';
export type { UserTitle } from './models/UserTitle';
export type { UserTitleStatus } from './models/UserTitleStatus';
export { DefaultService } from './services/DefaultService';

View file

@ -0,0 +1,9 @@
/* generated using openapi-typescript-codegen -- do not edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type CursorObj = {
id: number;
param?: string;
};

View file

@ -0,0 +1,10 @@
/* generated using openapi-typescript-codegen -- do not edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type Image = {
id?: number;
storage_type?: string;
image_path?: string;
};

View file

@ -0,0 +1,8 @@
/* generated using openapi-typescript-codegen -- do not edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
/**
* Title release season
*/
export type ReleaseSeason = 'winter' | 'spring' | 'summer' | 'fall';

View file

@ -0,0 +1,12 @@
/* generated using openapi-typescript-codegen -- do not edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
import type { Image } from './Image';
export type Studio = {
id: number;
name: string;
poster?: Image;
description?: string;
};

View file

@ -2,4 +2,7 @@
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type Tag = Record<string, any>;
/**
* A localized tag: keys are language codes (ISO 639-1), values are tag names
*/
export type Tag = Record<string, string>;

View file

@ -0,0 +1,9 @@
/* generated using openapi-typescript-codegen -- do not edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
import type { Tag } from './Tag';
/**
* Array of localized tags
*/
export type Tags = Array<Tag>;

View file

@ -0,0 +1,8 @@
/* generated using openapi-typescript-codegen -- do not edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
/**
* Title sort order
*/
export type TitleSort = 'id' | 'year' | 'rating' | 'views';

View file

@ -0,0 +1,8 @@
/* generated using openapi-typescript-codegen -- do not edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
/**
* Title status
*/
export type TitleStatus = 'finished' | 'ongoing' | 'planned';

View file

@ -10,7 +10,7 @@ export type User = {
/**
* ID of the user avatar (references images table)
*/
avatar_id?: number | null;
avatar_id?: number;
/**
* User email
*/
@ -30,6 +30,6 @@ export type User = {
/**
* Timestamp when the user was created
*/
creation_date: string;
creation_date?: string;
};

View file

@ -0,0 +1,8 @@
/* generated using openapi-typescript-codegen -- do not edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
/**
* User's title status
*/
export type UserTitleStatus = 'finished' | 'planned' | 'dropped' | 'in-progress';

View file

@ -0,0 +1,5 @@
/* generated using openapi-typescript-codegen -- do not edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type cursor = string;

View file

@ -0,0 +1,6 @@
/* generated using openapi-typescript-codegen -- do not edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
import type { TitleSort } from './TitleSort';
export type title_sort = TitleSort;

View file

@ -2,11 +2,102 @@
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
import type { CursorObj } from '../models/CursorObj';
import type { ReleaseSeason } from '../models/ReleaseSeason';
import type { Title } from '../models/Title';
import type { TitleSort } from '../models/TitleSort';
import type { TitleStatus } from '../models/TitleStatus';
import type { User } from '../models/User';
import type { UserTitle } from '../models/UserTitle';
import type { UserTitleStatus } from '../models/UserTitleStatus';
import type { CancelablePromise } from '../core/CancelablePromise';
import { OpenAPI } from '../core/OpenAPI';
import { request as __request } from '../core/request';
export class DefaultService {
/**
* Get titles
* @param cursor
* @param sort
* @param sortForward
* @param word
* @param status
* @param rating
* @param releaseYear
* @param releaseSeason
* @param limit
* @param offset
* @param fields
* @returns any List of titles with cursor
* @throws ApiError
*/
public static getTitles(
cursor?: string,
sort?: TitleSort,
sortForward: boolean = true,
word?: string,
status?: TitleStatus,
rating?: number,
releaseYear?: number,
releaseSeason?: ReleaseSeason,
limit: number = 10,
offset?: number,
fields: string = 'all',
): CancelablePromise<{
/**
* List of titles
*/
data: Array<Title>;
cursor: CursorObj;
}> {
return __request(OpenAPI, {
method: 'GET',
url: '/titles',
query: {
'cursor': cursor,
'sort': sort,
'sort_forward': sortForward,
'word': word,
'status': status,
'rating': rating,
'release_year': releaseYear,
'release_season': releaseSeason,
'limit': limit,
'offset': offset,
'fields': fields,
},
errors: {
400: `Request params are not correct`,
500: `Unknown server error`,
},
});
}
/**
* Get title description
* @param titleId
* @param fields
* @returns Title Title description
* @throws ApiError
*/
public static getTitles1(
titleId: number,
fields: string = 'all',
): CancelablePromise<Title> {
return __request(OpenAPI, {
method: 'GET',
url: '/titles/{title_id}',
path: {
'title_id': titleId,
},
query: {
'fields': fields,
},
errors: {
400: `Request params are not correct`,
404: `Title not found`,
500: `Unknown server error`,
},
});
}
/**
* Get user info
* @param userId
@ -28,7 +119,59 @@ export class DefaultService {
'fields': fields,
},
errors: {
400: `Request params are not correct`,
404: `User not found`,
500: `Unknown server error`,
},
});
}
/**
* Get user titles
* @param userId
* @param cursor
* @param word
* @param status
* @param watchStatus
* @param rating
* @param releaseYear
* @param releaseSeason
* @param limit
* @param fields
* @returns UserTitle List of user titles
* @throws ApiError
*/
public static getUsersTitles(
userId: string,
cursor?: string,
word?: string,
status?: TitleStatus,
watchStatus?: UserTitleStatus,
rating?: number,
releaseYear?: number,
releaseSeason?: ReleaseSeason,
limit: number = 10,
fields: string = 'all',
): CancelablePromise<Array<UserTitle>> {
return __request(OpenAPI, {
method: 'GET',
url: '/users/{user_id}/titles/',
path: {
'user_id': userId,
},
query: {
'cursor': cursor,
'word': word,
'status': status,
'watch_status': watchStatus,
'rating': rating,
'release_year': releaseYear,
'release_season': releaseSeason,
'limit': limit,
'fields': fields,
},
errors: {
400: `Request params are not correct`,
500: `Unknown server error`,
},
});
}

View file

@ -0,0 +1,25 @@
/* generated using openapi-typescript-codegen -- do not edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
import type { ApiRequestOptions } from './ApiRequestOptions';
import type { ApiResult } from './ApiResult';
export class ApiError extends Error {
public readonly url: string;
public readonly status: number;
public readonly statusText: string;
public readonly body: any;
public readonly request: ApiRequestOptions;
constructor(request: ApiRequestOptions, response: ApiResult, message: string) {
super(message);
this.name = 'ApiError';
this.url = response.url;
this.status = response.status;
this.statusText = response.statusText;
this.body = response.body;
this.request = request;
}
}

View file

@ -0,0 +1,17 @@
/* generated using openapi-typescript-codegen -- do not edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type ApiRequestOptions = {
readonly method: 'GET' | 'PUT' | 'POST' | 'DELETE' | 'OPTIONS' | 'HEAD' | 'PATCH';
readonly url: string;
readonly path?: Record<string, any>;
readonly cookies?: Record<string, any>;
readonly headers?: Record<string, any>;
readonly query?: Record<string, any>;
readonly formData?: Record<string, any>;
readonly body?: any;
readonly mediaType?: string;
readonly responseHeader?: string;
readonly errors?: Record<number, string>;
};

View file

@ -0,0 +1,11 @@
/* generated using openapi-typescript-codegen -- do not edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type ApiResult = {
readonly url: string;
readonly ok: boolean;
readonly status: number;
readonly statusText: string;
readonly body: any;
};

View file

@ -0,0 +1,131 @@
/* generated using openapi-typescript-codegen -- do not edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export class CancelError extends Error {
constructor(message: string) {
super(message);
this.name = 'CancelError';
}
public get isCancelled(): boolean {
return true;
}
}
export interface OnCancel {
readonly isResolved: boolean;
readonly isRejected: boolean;
readonly isCancelled: boolean;
(cancelHandler: () => void): void;
}
export class CancelablePromise<T> implements Promise<T> {
#isResolved: boolean;
#isRejected: boolean;
#isCancelled: boolean;
readonly #cancelHandlers: (() => void)[];
readonly #promise: Promise<T>;
#resolve?: (value: T | PromiseLike<T>) => void;
#reject?: (reason?: any) => void;
constructor(
executor: (
resolve: (value: T | PromiseLike<T>) => void,
reject: (reason?: any) => void,
onCancel: OnCancel
) => void
) {
this.#isResolved = false;
this.#isRejected = false;
this.#isCancelled = false;
this.#cancelHandlers = [];
this.#promise = new Promise<T>((resolve, reject) => {
this.#resolve = resolve;
this.#reject = reject;
const onResolve = (value: T | PromiseLike<T>): void => {
if (this.#isResolved || this.#isRejected || this.#isCancelled) {
return;
}
this.#isResolved = true;
if (this.#resolve) this.#resolve(value);
};
const onReject = (reason?: any): void => {
if (this.#isResolved || this.#isRejected || this.#isCancelled) {
return;
}
this.#isRejected = true;
if (this.#reject) this.#reject(reason);
};
const onCancel = (cancelHandler: () => void): void => {
if (this.#isResolved || this.#isRejected || this.#isCancelled) {
return;
}
this.#cancelHandlers.push(cancelHandler);
};
Object.defineProperty(onCancel, 'isResolved', {
get: (): boolean => this.#isResolved,
});
Object.defineProperty(onCancel, 'isRejected', {
get: (): boolean => this.#isRejected,
});
Object.defineProperty(onCancel, 'isCancelled', {
get: (): boolean => this.#isCancelled,
});
return executor(onResolve, onReject, onCancel as OnCancel);
});
}
get [Symbol.toStringTag]() {
return "Cancellable Promise";
}
public then<TResult1 = T, TResult2 = never>(
onFulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null,
onRejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null
): Promise<TResult1 | TResult2> {
return this.#promise.then(onFulfilled, onRejected);
}
public catch<TResult = never>(
onRejected?: ((reason: any) => TResult | PromiseLike<TResult>) | null
): Promise<T | TResult> {
return this.#promise.catch(onRejected);
}
public finally(onFinally?: (() => void) | null): Promise<T> {
return this.#promise.finally(onFinally);
}
public cancel(): void {
if (this.#isResolved || this.#isRejected || this.#isCancelled) {
return;
}
this.#isCancelled = true;
if (this.#cancelHandlers.length) {
try {
for (const cancelHandler of this.#cancelHandlers) {
cancelHandler();
}
} catch (error) {
console.warn('Cancellation threw an error', error);
return;
}
}
this.#cancelHandlers.length = 0;
if (this.#reject) this.#reject(new CancelError('Request aborted'));
}
public get isCancelled(): boolean {
return this.#isCancelled;
}
}

View file

@ -0,0 +1,32 @@
/* generated using openapi-typescript-codegen -- do not edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
import type { ApiRequestOptions } from './ApiRequestOptions';
type Resolver<T> = (options: ApiRequestOptions) => Promise<T>;
type Headers = Record<string, string>;
export type OpenAPIConfig = {
BASE: string;
VERSION: string;
WITH_CREDENTIALS: boolean;
CREDENTIALS: 'include' | 'omit' | 'same-origin';
TOKEN?: string | Resolver<string> | undefined;
USERNAME?: string | Resolver<string> | undefined;
PASSWORD?: string | Resolver<string> | undefined;
HEADERS?: Headers | Resolver<Headers> | undefined;
ENCODE_PATH?: ((path: string) => string) | undefined;
};
export const OpenAPI: OpenAPIConfig = {
BASE: 'http://127.0.0.1:8082',
VERSION: '1.0.0',
WITH_CREDENTIALS: false,
CREDENTIALS: 'include',
TOKEN: undefined,
USERNAME: undefined,
PASSWORD: undefined,
HEADERS: undefined,
ENCODE_PATH: undefined,
};

View file

@ -0,0 +1,323 @@
/* generated using openapi-typescript-codegen -- do not edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
import axios from 'axios';
import type { AxiosError, AxiosRequestConfig, AxiosResponse, AxiosInstance } from 'axios';
import FormData from 'form-data';
import { ApiError } from './ApiError';
import type { ApiRequestOptions } from './ApiRequestOptions';
import type { ApiResult } from './ApiResult';
import { CancelablePromise } from './CancelablePromise';
import type { OnCancel } from './CancelablePromise';
import type { OpenAPIConfig } from './OpenAPI';
export const isDefined = <T>(value: T | null | undefined): value is Exclude<T, null | undefined> => {
return value !== undefined && value !== null;
};
export const isString = (value: any): value is string => {
return typeof value === 'string';
};
export const isStringWithValue = (value: any): value is string => {
return isString(value) && value !== '';
};
export const isBlob = (value: any): value is Blob => {
return (
typeof value === 'object' &&
typeof value.type === 'string' &&
typeof value.stream === 'function' &&
typeof value.arrayBuffer === 'function' &&
typeof value.constructor === 'function' &&
typeof value.constructor.name === 'string' &&
/^(Blob|File)$/.test(value.constructor.name) &&
/^(Blob|File)$/.test(value[Symbol.toStringTag])
);
};
export const isFormData = (value: any): value is FormData => {
return value instanceof FormData;
};
export const isSuccess = (status: number): boolean => {
return status >= 200 && status < 300;
};
export const base64 = (str: string): string => {
try {
return btoa(str);
} catch (err) {
// @ts-ignore
return Buffer.from(str).toString('base64');
}
};
export const getQueryString = (params: Record<string, any>): string => {
const qs: string[] = [];
const append = (key: string, value: any) => {
qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);
};
const process = (key: string, value: any) => {
if (isDefined(value)) {
if (Array.isArray(value)) {
value.forEach(v => {
process(key, v);
});
} else if (typeof value === 'object') {
Object.entries(value).forEach(([k, v]) => {
process(`${key}[${k}]`, v);
});
} else {
append(key, value);
}
}
};
Object.entries(params).forEach(([key, value]) => {
process(key, value);
});
if (qs.length > 0) {
return `?${qs.join('&')}`;
}
return '';
};
const getUrl = (config: OpenAPIConfig, options: ApiRequestOptions): string => {
const encoder = config.ENCODE_PATH || encodeURI;
const path = options.url
.replace('{api-version}', config.VERSION)
.replace(/{(.*?)}/g, (substring: string, group: string) => {
if (options.path?.hasOwnProperty(group)) {
return encoder(String(options.path[group]));
}
return substring;
});
const url = `${config.BASE}${path}`;
if (options.query) {
return `${url}${getQueryString(options.query)}`;
}
return url;
};
export const getFormData = (options: ApiRequestOptions): FormData | undefined => {
if (options.formData) {
const formData = new FormData();
const process = (key: string, value: any) => {
if (isString(value) || isBlob(value)) {
formData.append(key, value);
} else {
formData.append(key, JSON.stringify(value));
}
};
Object.entries(options.formData)
.filter(([_, value]) => isDefined(value))
.forEach(([key, value]) => {
if (Array.isArray(value)) {
value.forEach(v => process(key, v));
} else {
process(key, value);
}
});
return formData;
}
return undefined;
};
type Resolver<T> = (options: ApiRequestOptions) => Promise<T>;
export const resolve = async <T>(options: ApiRequestOptions, resolver?: T | Resolver<T>): Promise<T | undefined> => {
if (typeof resolver === 'function') {
return (resolver as Resolver<T>)(options);
}
return resolver;
};
export const getHeaders = async (config: OpenAPIConfig, options: ApiRequestOptions, formData?: FormData): Promise<Record<string, string>> => {
const [token, username, password, additionalHeaders] = await Promise.all([
resolve(options, config.TOKEN),
resolve(options, config.USERNAME),
resolve(options, config.PASSWORD),
resolve(options, config.HEADERS),
]);
const formHeaders = typeof formData?.getHeaders === 'function' && formData?.getHeaders() || {}
const headers = Object.entries({
Accept: 'application/json',
...additionalHeaders,
...options.headers,
...formHeaders,
})
.filter(([_, value]) => isDefined(value))
.reduce((headers, [key, value]) => ({
...headers,
[key]: String(value),
}), {} as Record<string, string>);
if (isStringWithValue(token)) {
headers['Authorization'] = `Bearer ${token}`;
}
if (isStringWithValue(username) && isStringWithValue(password)) {
const credentials = base64(`${username}:${password}`);
headers['Authorization'] = `Basic ${credentials}`;
}
if (options.body !== undefined) {
if (options.mediaType) {
headers['Content-Type'] = options.mediaType;
} else if (isBlob(options.body)) {
headers['Content-Type'] = options.body.type || 'application/octet-stream';
} else if (isString(options.body)) {
headers['Content-Type'] = 'text/plain';
} else if (!isFormData(options.body)) {
headers['Content-Type'] = 'application/json';
}
}
return headers;
};
export const getRequestBody = (options: ApiRequestOptions): any => {
if (options.body) {
return options.body;
}
return undefined;
};
export const sendRequest = async <T>(
config: OpenAPIConfig,
options: ApiRequestOptions,
url: string,
body: any,
formData: FormData | undefined,
headers: Record<string, string>,
onCancel: OnCancel,
axiosClient: AxiosInstance
): Promise<AxiosResponse<T>> => {
const source = axios.CancelToken.source();
const requestConfig: AxiosRequestConfig = {
url,
headers,
data: body ?? formData,
method: options.method,
withCredentials: config.WITH_CREDENTIALS,
withXSRFToken: config.CREDENTIALS === 'include' ? config.WITH_CREDENTIALS : false,
cancelToken: source.token,
};
onCancel(() => source.cancel('The user aborted a request.'));
try {
return await axiosClient.request(requestConfig);
} catch (error) {
const axiosError = error as AxiosError<T>;
if (axiosError.response) {
return axiosError.response;
}
throw error;
}
};
export const getResponseHeader = (response: AxiosResponse<any>, responseHeader?: string): string | undefined => {
if (responseHeader) {
const content = response.headers[responseHeader];
if (isString(content)) {
return content;
}
}
return undefined;
};
export const getResponseBody = (response: AxiosResponse<any>): any => {
if (response.status !== 204) {
return response.data;
}
return undefined;
};
export const catchErrorCodes = (options: ApiRequestOptions, result: ApiResult): void => {
const errors: Record<number, string> = {
400: 'Bad Request',
401: 'Unauthorized',
403: 'Forbidden',
404: 'Not Found',
500: 'Internal Server Error',
502: 'Bad Gateway',
503: 'Service Unavailable',
...options.errors,
}
const error = errors[result.status];
if (error) {
throw new ApiError(options, result, error);
}
if (!result.ok) {
const errorStatus = result.status ?? 'unknown';
const errorStatusText = result.statusText ?? 'unknown';
const errorBody = (() => {
try {
return JSON.stringify(result.body, null, 2);
} catch (e) {
return undefined;
}
})();
throw new ApiError(options, result,
`Generic Error: status: ${errorStatus}; status text: ${errorStatusText}; body: ${errorBody}`
);
}
};
/**
* Request method
* @param config The OpenAPI configuration object
* @param options The request options from the service
* @param axiosClient The axios client instance to use
* @returns CancelablePromise<T>
* @throws ApiError
*/
export const request = <T>(config: OpenAPIConfig, options: ApiRequestOptions, axiosClient: AxiosInstance = axios): CancelablePromise<T> => {
return new CancelablePromise(async (resolve, reject, onCancel) => {
try {
const url = getUrl(config, options);
const formData = getFormData(options);
const body = getRequestBody(options);
const headers = await getHeaders(config, options, formData);
if (!onCancel.isCancelled) {
const response = await sendRequest<T>(config, options, url, body, formData, headers, onCancel, axiosClient);
const responseBody = getResponseBody(response);
const responseHeader = getResponseHeader(response, options.responseHeader);
const result: ApiResult = {
url,
ok: isSuccess(response.status),
status: response.status,
statusText: response.statusText,
body: responseHeader ?? responseBody,
};
catchErrorCodes(options, result);
resolve(result.body);
}
} catch (error) {
reject(error);
}
});
};

View file

@ -0,0 +1,10 @@
/* generated using openapi-typescript-codegen -- do not edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export { ApiError } from './core/ApiError';
export { CancelablePromise, CancelError } from './core/CancelablePromise';
export { OpenAPI } from './core/OpenAPI';
export type { OpenAPIConfig } from './core/OpenAPI';
export { AuthService } from './services/AuthService';

View file

@ -0,0 +1,58 @@
/* generated using openapi-typescript-codegen -- do not edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
import type { CancelablePromise } from '../core/CancelablePromise';
import { OpenAPI } from '../core/OpenAPI';
import { request as __request } from '../core/request';
export class AuthService {
/**
* Sign up a new user
* @param requestBody
* @returns any Sign-up result
* @throws ApiError
*/
public static postAuthSignUp(
requestBody: {
nickname: string;
pass: string;
},
): CancelablePromise<{
success?: boolean;
error?: string | null;
user_id?: string | null;
}> {
return __request(OpenAPI, {
method: 'POST',
url: '/auth/sign-up',
body: requestBody,
mediaType: 'application/json',
});
}
/**
* Sign in a user and return JWT
* @param requestBody
* @returns any Sign-in result with JWT
* @throws ApiError
*/
public static postAuthSignIn(
requestBody: {
nickname: string;
pass: string;
},
): CancelablePromise<{
success?: boolean;
error?: string | null;
user_id?: string | null;
}> {
return __request(OpenAPI, {
method: 'POST',
url: '/auth/sign-in',
body: requestBody,
mediaType: 'application/json',
errors: {
401: `Access denied due to invalid credentials`,
},
});
}
}

View file

@ -0,0 +1,90 @@
import React, { useState } from "react";
import { Link } from "react-router-dom";
import { Bars3Icon, XMarkIcon } from "@heroicons/react/24/solid";
type HeaderProps = {
username?: string;
};
export const Header: React.FC<HeaderProps> = ({ username }) => {
const [menuOpen, setMenuOpen] = useState(false);
const toggleMenu = () => setMenuOpen(!menuOpen);
return (
<header className="w-full bg-white shadow-md fixed top-0 left-0 z-50">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="flex justify-between h-16 items-center">
{/* Левый блок — логотип / название */}
<div className="flex-shrink-0">
<Link to="/" className="text-xl font-bold text-gray-800 hover:text-blue-600">
NyanimeDB
</Link>
</div>
{/* Центр — ссылки на разделы (desktop) */}
<nav className="hidden md:flex space-x-4">
<Link to="/titles" className="text-gray-700 hover:text-blue-600">
Titles
</Link>
<Link to="/users" className="text-gray-700 hover:text-blue-600">
Users
</Link>
<Link to="/about" className="text-gray-700 hover:text-blue-600">
About
</Link>
</nav>
{/* Правый блок — профиль */}
<div className="hidden md:flex items-center space-x-4">
{username ? (
<Link to="/profile" className="text-gray-700 hover:text-blue-600 font-medium">
{username}
</Link>
) : (
<Link to="/login" className="text-gray-700 hover:text-blue-600 font-medium">
Login
</Link>
)}
</div>
{/* Бургер для мобильного */}
<div className="md:hidden flex items-center">
<button
onClick={toggleMenu}
className="p-2 rounded-md hover:bg-gray-200 transition"
>
{menuOpen ? (
<XMarkIcon className="w-6 h-6 text-gray-800" />
) : (
<Bars3Icon className="w-6 h-6 text-gray-800" />
)}
</button>
</div>
</div>
</div>
{/* Мобильное меню */}
{menuOpen && (
<div className="md:hidden bg-white border-t border-gray-200 shadow-md">
<nav className="flex flex-col p-4 space-y-2">
<Link to="/titles" className="text-gray-700 hover:text-blue-600" onClick={() => setMenuOpen(false)}>Titles</Link>
<Link to="/users" className="text-gray-700 hover:text-blue-600" onClick={() => setMenuOpen(false)}>Users</Link>
<Link to="/about" className="text-gray-700 hover:text-blue-600" onClick={() => setMenuOpen(false)}>About</Link>
{username ? (
<Link to="/profile" className="text-gray-700 hover:text-blue-600 font-medium" onClick={() => setMenuOpen(false)}>
{username}
</Link>
) : (
<Link to="/login" className="text-gray-700 hover:text-blue-600 font-medium" onClick={() => setMenuOpen(false)}>
Login
</Link>
)}
</nav>
</div>
)}
</header>
);
};

View file

@ -0,0 +1,28 @@
import React from "react";
import { Squares2X2Icon, Bars3Icon } from "@heroicons/react/24/solid";
export type LayoutSwitchProps = {
layout: "square" | "horizontal"
setLayout: (value: React.SetStateAction<"square" | "horizontal">) => void
};
export function LayoutSwitch({
layout,
setLayout
}: LayoutSwitchProps) {
return (
<div className="flex justify-end">
<button
className="p-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition"
onClick={() =>
setLayout(prev => (prev === "square" ? "horizontal" : "square"))
}>
{layout === "square"
? <Squares2X2Icon className="w-6 h-6" />
: <Bars3Icon className="w-6 h-6" />
}
</button>
</div>
);
}

View file

@ -0,0 +1,48 @@
import React from "react";
export type ListViewProps<T> = {
items: T[];
layout: "square" | "horizontal";
renderItem: (item: T, layout: "square" | "horizontal") => React.ReactNode;
onLoadMore: () => void;
hasMore: boolean;
loadingMore: boolean;
};
export function ListView<T>({
items,
layout,
renderItem,
onLoadMore,
hasMore,
loadingMore
}: ListViewProps<T>) {
return (
<div className="w-full flex flex-col items-center">
{/* Items */}
<div
className={`w-full sm:w-4/5 grid gap-6 ${
layout === "square"
? "grid-cols-1 sm:grid-cols-2 lg:grid-cols-4"
: "grid-cols-1"
}`}
>
{items.map(item => renderItem(item, layout))}
</div>
{/* Load More */}
{hasMore && (
<div className="mt-8">
<button
className="px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition disabled:opacity-50"
disabled={loadingMore}
onClick={onLoadMore}
>
{loadingMore ? "Loading..." : "Load More"}
</button>
</div>
)}
</div>
);
}

View file

@ -0,0 +1,34 @@
type SearchBarProps = {
placeholder?: string;
search: string;
setSearch: (value: string) => void;
};
export function SearchBar({
placeholder = "Search...",
search,
setSearch,
}: SearchBarProps) {
return (
<div className="w-full">
<input
type="text"
value={search}
placeholder={placeholder}
onChange={(e) => setSearch(e.target.value)}
className="
w-full
px-4
py-2
border
border-gray-300
rounded-lg
focus:outline-none
focus:ring-2
focus:ring-blue-500
text-black
"
/>
</div>
);
}

View file

@ -0,0 +1,67 @@
import { useState } from "react";
import type { TitleSort } from "../../api";
import { ChevronDownIcon, ArrowUpIcon, ArrowDownIcon } from "@heroicons/react/24/solid";
type TitlesSortBoxProps = {
sort: TitleSort;
setSort: (value: TitleSort) => void;
sortForward: boolean;
setSortForward: (value: boolean) => void;
};
const SORT_OPTIONS: TitleSort[] = ["id", "rating", "year", "views"];
export function TitlesSortBox({
sort,
setSort,
sortForward,
setSortForward,
}: TitlesSortBoxProps) {
const [open, setOpen] = useState(false);
const toggleSortDirection = () => setSortForward(!sortForward);
const handleSortSelect = (newSort: TitleSort) => {
setSort(newSort);
setOpen(false);
};
return (
<div className="inline-flex relative z-50">
{/* Левая часть — смена направления */}
<button
onClick={toggleSortDirection}
className="px-4 py-2 flex items-center justify-center bg-gray-100 hover:bg-gray-200 border border-gray-300 rounded-l-lg transition"
>
{sortForward ? <ArrowUpIcon className="w-4 h-4 mr-1" /> : <ArrowDownIcon className="w-4 h-4 mr-1" />}
<span className="text-sm font-medium">Order</span>
</button>
{/* Правая часть — выбор параметра */}
<button
onClick={() => setOpen(!open)}
className="px-4 py-2 flex items-center justify-center bg-gray-100 hover:bg-gray-200 border border-gray-300 border-l-0 rounded-r-lg transition"
>
<span className="text-sm font-medium">{sort}</span>
<ChevronDownIcon className="w-4 h-4 ml-1" />
</button>
{/* Dropdown */}
{open && (
<ul className="absolute top-full left-0 mt-1 w-40 bg-white border border-gray-300 rounded-md shadow-lg z-[1000]">
{SORT_OPTIONS.map(option => (
<li key={option}>
<button
className={`w-full text-left px-4 py-2 hover:bg-gray-100 transition ${
option === sort ? "font-bold bg-gray-100" : ""
}`}
onClick={() => handleSortSelect(option)}
>
{option}
</button>
</li>
))}
</ul>
)}
</div>
);
}

View file

@ -1,97 +0,0 @@
.container {
display: flex;
justify-content: center;
align-items: flex-start;
padding: 3rem 1rem;
background-color: #f5f6fa;
min-height: 100vh;
font-family: "Inter", sans-serif;
}
.card {
background-color: #ffffff;
border-radius: 1rem;
box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
padding: 2rem;
max-width: 400px;
width: 100%;
display: flex;
flex-direction: column;
align-items: center;
text-align: center;
}
.avatar {
margin-bottom: 1.5rem;
}
.avatarImg {
width: 120px;
height: 120px;
border-radius: 50%;
object-fit: cover;
border: 3px solid #4a90e2;
}
.avatarPlaceholder {
width: 120px;
height: 120px;
border-radius: 50%;
background-color: #dcdde1;
display: flex;
align-items: center;
justify-content: center;
font-size: 3rem;
color: #4a4a4a;
font-weight: bold;
border: 3px solid #4a90e2;
}
.info {
display: flex;
flex-direction: column;
align-items: center;
}
.name {
font-size: 1.8rem;
font-weight: 700;
margin: 0.25rem 0;
color: #2f3640;
}
.nickname {
font-size: 1rem;
color: #718093;
margin-bottom: 1rem;
}
.desc {
font-size: 1rem;
color: #353b48;
margin-bottom: 1rem;
}
.created {
font-size: 0.9rem;
color: #7f8fa6;
}
.loader {
display: flex;
justify-content: center;
align-items: center;
height: 80vh;
font-size: 1.5rem;
color: #4a90e2;
}
.error {
display: flex;
justify-content: center;
align-items: center;
height: 80vh;
color: #e84118;
font-weight: 600;
font-size: 1.2rem;
}

View file

@ -0,0 +1,22 @@
import type { Title } from "../../api/models/Title";
export function TitleCardHorizontal({ title }: { title: Title }) {
return (
<div style={{
display: "flex",
gap: 12,
padding: 12,
border: "1px solid #ddd",
borderRadius: 8
}}>
{title.poster?.image_path && (
<img src={title.poster.image_path} width={80} />
)}
<div>
<h3>{title.title_names["en"]}</h3>
<p>{title.release_year} · {title.release_season} · Rating: {title.rating}</p>
<p>Status: {title.title_status}</p>
</div>
</div>
);
}

View file

@ -0,0 +1,22 @@
// TitleCardSquare.tsx
import type { Title } from "../../api/models/Title";
export function TitleCardSquare({ title }: { title: Title }) {
return (
<div style={{
width: 160,
border: "1px solid #ddd",
padding: 8,
borderRadius: 8,
textAlign: "center"
}}>
{title.poster?.image_path && (
<img src={title.poster.image_path} width={140} />
)}
<div>
<h4>{title.title_names["en"]}</h4>
<small>{title.release_year} {title.rating}</small>
</div>
</div>
);
}

View file

@ -1,68 +1,9 @@
:root {
font-family: system-ui, Avenir, Helvetica, Arial, sans-serif;
line-height: 1.5;
font-weight: 400;
@import "tailwindcss";
color-scheme: light dark;
color: rgba(255, 255, 255, 0.87);
background-color: #242424;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
a {
font-weight: 500;
color: #646cff;
text-decoration: inherit;
}
a:hover {
color: #535bf2;
}
body {
html, body, #root {
margin: 0;
display: flex;
place-items: center;
min-width: 320px;
min-height: 100vh;
}
h1 {
font-size: 3.2em;
line-height: 1.1;
}
button {
border-radius: 8px;
border: 1px solid transparent;
padding: 0.6em 1.2em;
font-size: 1em;
font-weight: 500;
font-family: inherit;
background-color: #1a1a1a;
cursor: pointer;
transition: border-color 0.25s;
}
button:hover {
border-color: #646cff;
}
button:focus,
button:focus-visible {
outline: 4px auto -webkit-focus-ring-color;
}
@media (prefers-color-scheme: light) {
:root {
color: #213547;
background-color: #ffffff;
}
a:hover {
color: #747bff;
}
button {
background-color: #f9f9f9;
}
padding: 0;
width: 100%;
height: 100%;
@apply text-black bg-white;
}

View file

@ -0,0 +1,116 @@
import React, { useState } from "react";
import { AuthService } from "../../auth/services/AuthService";
import { useNavigate } from "react-router-dom";
export const LoginPage: React.FC = () => {
const navigate = useNavigate();
const [isLogin, setIsLogin] = useState(true); // true = login, false = signup
const [nickname, setNickname] = useState("");
const [password, setPassword] = useState("");
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setLoading(true);
setError(null);
try {
if (isLogin) {
const res = await AuthService.postAuthSignIn({ nickname, pass: password });
if (res.success) {
// TODO: сохранить JWT в localStorage/cookie
console.log("Logged in user id:", res.user_id);
navigate("/"); // редирект после успешного входа
} else {
setError(res.error || "Login failed");
}
} else {
const res = await AuthService.postAuthSignUp({ nickname, pass: password });
if (res.success) {
console.log("User signed up with id:", res.user_id);
setIsLogin(true); // переключаемся на login после регистрации
} else {
setError(res.error || "Sign up failed");
}
}
} catch (err: any) {
console.error(err);
setError(err?.message || "Something went wrong");
} finally {
setLoading(false);
}
};
return (
<div className="min-h-screen flex items-center justify-center bg-gray-50 px-4">
<div className="max-w-md w-full bg-white shadow-md rounded-lg p-8">
<h2 className="text-2xl font-bold mb-6 text-center">
{isLogin ? "Login" : "Sign Up"}
</h2>
{error && <div className="text-red-600 mb-4">{error}</div>}
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Nickname
</label>
<input
type="text"
value={nickname}
onChange={(e) => setNickname(e.target.value)}
className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
required
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Password
</label>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
required
/>
</div>
<button
type="submit"
disabled={loading}
className="w-full bg-blue-600 text-white py-2 rounded-lg font-semibold hover:bg-blue-700 transition disabled:opacity-50"
>
{loading ? "Please wait..." : isLogin ? "Login" : "Sign Up"}
</button>
</form>
<div className="mt-4 text-center text-sm text-gray-600">
{isLogin ? (
<>
Don't have an account?{" "}
<button
onClick={() => setIsLogin(false)}
className="text-blue-600 hover:underline"
>
Sign Up
</button>
</>
) : (
<>
Already have an account?{" "}
<button
onClick={() => setIsLogin(true)}
className="text-blue-600 hover:underline"
>
Login
</button>
</>
)}
</div>
</div>
</div>
);
};

View file

@ -0,0 +1,64 @@
// import React, { useEffect, useState } from "react";
// import { useParams } from "react-router-dom";
// import { DefaultService } from "../../api/services/DefaultService";
// import type { User } from "../../api/models/User";
// import styles from "./UserPage.module.css";
// const UserPage: React.FC = () => {
// const { id } = useParams<{ id: string }>();
// const [user, setUser] = useState<User | null>(null);
// const [loading, setLoading] = useState(true);
// const [error, setError] = useState<string | null>(null);
// useEffect(() => {
// if (!id) return;
// const getTitleInfo = async () => {
// try {
// const userInfo = await DefaultService.getTitle(id, "all");
// setUser(userInfo);
// } catch (err) {
// console.error(err);
// setError("Failed to fetch user info.");
// } finally {
// setLoading(false);
// }
// };
// getTitleInfo();
// }, [id]);
// if (loading) return <div className={styles.loader}>Loading...</div>;
// if (error) return <div className={styles.error}>{error}</div>;
// if (!user) return <div className={styles.error}>User not found.</div>;
// return (
// <div className={styles.container}>
// <div className={styles.card}>
// <div className={styles.avatar}>
// {user.avatar_id ? (
// <img
// src={`/images/${user.avatar_id}.png`}
// alt="User Avatar"
// className={styles.avatarImg}
// />
// ) : (
// <div className={styles.avatarPlaceholder}>
// {user.disp_name?.[0] || "U"}
// </div>
// )}
// </div>
// <div className={styles.info}>
// <h1 className={styles.name}>{user.disp_name || user.nickname}</h1>
// <p className={styles.nickname}>@{user.nickname}</p>
// {user.user_desc && <p className={styles.desc}>{user.user_desc}</p>}
// <p className={styles.created}>
// Joined: {new Date(user.creation_date).toLocaleDateString()}
// </p>
// </div>
// </div>
// </div>
// );
// };
// export default UserPage;

View file

@ -0,0 +1 @@
@import "tailwindcss";

View file

@ -0,0 +1,154 @@
import { useEffect, useState } from "react";
import { ListView } from "../../components/ListView/ListView";
import { SearchBar } from "../../components/SearchBar/SearchBar";
import { TitlesSortBox } from "../../components/TitlesSortBox/TitlesSortBox";
import { DefaultService } from "../../api/services/DefaultService";
import { TitleCardSquare } from "../../components/cards/TitleCardSquare";
import { TitleCardHorizontal } from "../../components/cards/TitleCardHorizontal";
import type { CursorObj, Title, TitleSort } from "../../api";
import { LayoutSwitch } from "../../components/LayoutSwitch/LayoutSwitch";
const PAGE_SIZE = 10;
export default function TitlesPage() {
const [titles, setTitles] = useState<Title[]>([]);
const [nextPage, setNextPage] = useState<Title[]>([]);
const [cursor, setCursor] = useState<CursorObj | null>(null);
const [search, setSearch] = useState("");
const [loading, setLoading] = useState(true);
const [loadingMore, setLoadingMore] = useState(false);
const [sort, setSort] = useState<TitleSort>("id");
const [sortForward, setSortForward] = useState(true);
const [layout, setLayout] = useState<"square" | "horizontal">("square");
const fetchPage = async (cursorObj: CursorObj | null) => {
const cursorStr = cursorObj ? btoa(JSON.stringify(cursorObj)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') : "";
try {
const result = await DefaultService.getTitles(
cursorStr,
sort,
sortForward,
search.trim() || undefined,
undefined,
undefined,
undefined,
undefined,
PAGE_SIZE,
undefined,
"all"
);
if ((result === undefined) || !result.data?.length) {
return { items: [], nextCursor: null };
}
return {
items: result.data ?? [],
nextCursor: result.cursor ?? null
};
} catch (err: any) {
if (err.status === 204) {
return { items: [], nextCursor: null };
}
throw err;
}
};
// Инициализация: загружаем сразу две страницы
useEffect(() => {
const initLoad = async () => {
setLoading(true);
setTitles([]);
setNextPage([]);
setCursor(null);
const firstPage = await fetchPage(null);
const secondPage = firstPage.nextCursor ? await fetchPage(firstPage.nextCursor) : { items: [], nextCursor: null };
setTitles(firstPage.items);
setNextPage(secondPage.items);
setCursor(secondPage.nextCursor);
setLoading(false);
};
initLoad();
}, [search, sort, sortForward]);
const handleLoadMore = async () => {
if (nextPage.length === 0) {
setLoadingMore(false);
return;
}
setLoadingMore(true);
setTitles(prev => [...prev, ...nextPage]);
setNextPage([]);
// Подгружаем следующую страницу с сервера
if (cursor) {
try {
const next = await fetchPage(cursor);
if (next.items.length > 0) {
setNextPage(next.items);
}
setCursor(next.nextCursor);
} catch (err) {
console.error(err);
}
}
// Любой сценарий выключаем loadingMore
setLoadingMore(false);
};
return (
<div className="w-full min-h-screen bg-gray-50 p-6 flex flex-col items-center">
<h1 className="text-4xl font-bold mb-6 text-center text-black">Titles</h1>
<div className="w-full sm:w-4/5 flex flex-col sm:flex-row gap-4 mb-6 items-center">
<SearchBar placeholder="Search titles..." search={search} setSearch={setSearch} />
<LayoutSwitch layout={layout} setLayout={setLayout} />
<TitlesSortBox
sort={sort}
setSort={setSort}
sortForward={sortForward}
setSortForward={setSortForward}
/>
</div>
{loading && <div className="mt-20 font-medium text-black">Loading...</div>}
{!loading && titles.length === 0 && (
<div className="mt-20 font-medium text-black">No titles found.</div>
)}
{titles.length > 0 && (
<>
<ListView<Title>
items={titles}
layout={layout}
hasMore={!!cursor || nextPage.length > 1}
loadingMore={loadingMore}
onLoadMore={handleLoadMore}
renderItem={(title, layout) =>
layout === "square"
? <TitleCardSquare title={title} />
: <TitleCardHorizontal title={title} />
}
/>
{!cursor && nextPage.length == 0 && (
<div className="mt-6 font-medium text-black">
Результатов больше нет, было найдено {titles.length} тайтлов.
</div>
)}
</>
)}
</div>
);
}

View file

@ -0,0 +1,103 @@
body,
html {
width: 100%;
margin: 0;
background-color: #777;
color: #fff;
}
html,
body,
#root {
height: 100%;
}
.header {
width: 100vw;
padding: 30px 40px;
background: #f7f7f7;
display: flex;
align-items: center;
gap: 25px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
border-bottom: 1px solid #e5e5e5;
color: #000000;
}
.avatarWrapper {
width: 120px;
height: 120px;
min-width: 120px;
border-radius: 50%;
overflow: hidden;
display: flex;
align-items: center;
justify-content: center;
background: #ddd;
}
.avatarImg {
width: 100%;
height: 100%;
object-fit: cover;
}
.avatarPlaceholder {
width: 100%;
height: 100%;
border-radius: 50%;
background: #ccc;
font-size: 42px;
font-weight: bold;
color: #555;
display: flex;
align-items: center;
justify-content: center;
}
.userInfo {
display: flex;
flex-direction: column;
}
.name {
font-size: 32px;
font-weight: 700;
margin: 0;
}
.nickname {
font-size: 18px;
color: #666;
margin-top: 6px;
}
.container {
max-width: 100vw;
width: 100%;
position: absolute;
top: 0%;
/* margin: 25px auto; */
/* padding: 0 20px; */
}
.content {
margin-top: 20px;
}
.desc {
font-size: 18px;
margin-bottom: 10px;
}
.created {
font-size: 16px;
color: #888;
}
.loader,
.error {
text-align: center;
margin-top: 40px;
font-size: 18px;
}

View file

@ -33,8 +33,8 @@ const UserPage: React.FC = () => {
return (
<div className={styles.container}>
<div className={styles.card}>
<div className={styles.avatar}>
<div className={styles.header}>
<div className={styles.avatarWrapper}>
{user.avatar_id ? (
<img
src={`/images/${user.avatar_id}.png`}
@ -48,13 +48,16 @@ const UserPage: React.FC = () => {
)}
</div>
<div className={styles.info}>
<div className={styles.userInfo}>
<h1 className={styles.name}>{user.disp_name || user.nickname}</h1>
<p className={styles.nickname}>@{user.nickname}</p>
{user.user_desc && <p className={styles.desc}>{user.user_desc}</p>}
<p className={styles.created}>
{/* <p className={styles.created}>
Joined: {new Date(user.creation_date).toLocaleDateString()}
</p>
</p> */}
</div>
<div className={styles.content}>
{user.user_desc && <p className={styles.desc}>{user.user_desc}</p>}
</div>
</div>
</div>

View file

@ -0,0 +1,12 @@
export interface PaginatedResult<TItem> {
items: TItem[];
nextCursor?: string;
}
export interface FetchParams {
search: string;
cursor?: string;
}
export type FetchFunction<TItem> =
(params: FetchParams) => Promise<PaginatedResult<TItem>>;

View file

@ -20,7 +20,7 @@
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"erasableSyntaxOnly": false,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},

View file

@ -18,7 +18,7 @@
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"erasableSyntaxOnly": false,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},

View file

@ -1,11 +1,15 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'
// https://vite.dev/config/
export default defineConfig({
plugins: [react()],
plugins: [
react(),
tailwindcss()
],
server: {
host: '127.0.0.1',
host: '0.0.0.0',
port: 8083,
},
})

View file

@ -14,6 +14,7 @@ CREATE TABLE providers (
CREATE TABLE tags (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
-- example: { "ru": "Сёдзё", "en": "Shojo", "jp": "少女"}
tag_names jsonb NOT NULL
);
@ -23,12 +24,27 @@ CREATE TABLE images (
image_path text UNIQUE NOT NULL
);
CREATE TABLE reviews (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
data text NOT NULL,
rating int CHECK (rating >= 0 AND rating <= 10),
user_id bigint REFERENCES users (id),
title_id bigint REFERENCES titles (id),
created_at timestamptz DEFAULT NOW()
);
CREATE TABLE review_images (
PRIMARY KEY (review_id, image_id),
review_id bigint NOT NULL REFERENCES reviews(id) ON DELETE CASCADE,
image_id bigint NOT NULL REFERENCES images(id) ON DELETE CASCADE
);
CREATE TABLE users (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
avatar_id bigint REFERENCES images (id),
passhash text NOT NULL,
mail text CHECK (mail ~ '[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9_-]+'),
nickname text NOT NULL CHECK (nickname ~ '^[a-zA-Z0-9_-]+$'),
mail text CHECK (mail ~ '^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9_-]+$'),
nickname text UNIQUE NOT NULL CHECK (nickname ~ '^[a-zA-Z0-9_-]{3,}$'),
disp_name text,
user_desc text,
creation_date timestamptz NOT NULL,
@ -37,13 +53,15 @@ CREATE TABLE users (
CREATE TABLE studios (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
studio_name text UNIQUE,
studio_name text NOT NULL UNIQUE,
illust_id bigint REFERENCES images (id),
studio_desc text
);
CREATE TABLE titles (
-- // TODO: anime type (film, season etc)
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
-- example {"ru": ["Атака титанов", "Атака Титанов"],"en": ["Attack on Titan", "AoT"],"ja": ["進撃の巨人", "しんげきのきょじん"]}
title_names jsonb NOT NULL,
studio_id bigint NOT NULL REFERENCES studios (id),
poster_id bigint REFERENCES images (id),
@ -55,6 +73,7 @@ CREATE TABLE titles (
season int CHECK (season >= 0),
episodes_aired int CHECK (episodes_aired >= 0),
episodes_all int CHECK (episodes_all >= 0),
-- example { "1": "50.50", "2": "23.23"}
episodes_len jsonb,
CHECK ((episodes_aired IS NULL AND episodes_all IS NULL)
OR (episodes_aired IS NOT NULL AND episodes_all IS NOT NULL
@ -67,8 +86,9 @@ CREATE TABLE usertitles (
title_id bigint NOT NULL REFERENCES titles (id),
status usertitle_status_t NOT NULL,
rate int CHECK (rate > 0 AND rate <= 10),
review_text text,
review_date timestamptz
review_id bigint REFERENCES reviews (id),
ctime timestamptz
-- // TODO: series status
);
CREATE TABLE title_tags (
@ -85,6 +105,17 @@ CREATE TABLE signals (
pending boolean NOT NULL
);
CREATE TABLE external_ids (
user_id bigint NOT NULL REFERENCES users (id),
service_id bigint REFERENCES external_services (id),
external_id text NOT NULL
);
CREATE TABLE external_services (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text UNIQUE NOT NULL
);
-- Functions
CREATE OR REPLACE FUNCTION update_title_rating()
RETURNS TRIGGER AS $$

View file

@ -185,6 +185,17 @@ func (ns NullUsertitleStatusT) Value() (driver.Value, error) {
return string(ns.UsertitleStatusT), nil
}
type ExternalID struct {
UserID int64 `json:"user_id"`
ServiceID *int64 `json:"service_id"`
ExternalID string `json:"external_id"`
}
type ExternalService struct {
ID int64 `json:"id"`
Name string `json:"name"`
}
type Image struct {
ID int64 `json:"id"`
StorageType StorageTypeT `json:"storage_type"`
@ -197,6 +208,20 @@ type Provider struct {
Credentials []byte `json:"credentials"`
}
type Review struct {
ID int64 `json:"id"`
Data string `json:"data"`
Rating *int32 `json:"rating"`
UserID *int64 `json:"user_id"`
TitleID *int64 `json:"title_id"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
}
type ReviewImage struct {
ReviewID int64 `json:"review_id"`
ImageID int64 `json:"image_id"`
}
type Signal struct {
ID int64 `json:"id"`
TitleID *int64 `json:"title_id"`
@ -207,7 +232,7 @@ type Signal struct {
type Studio struct {
ID int64 `json:"id"`
StudioName *string `json:"studio_name"`
StudioName string `json:"studio_name"`
IllustID *int64 `json:"illust_id"`
StudioDesc *string `json:"studio_desc"`
}
@ -226,7 +251,7 @@ type Title struct {
Rating *float64 `json:"rating"`
RatingCount *int32 `json:"rating_count"`
ReleaseYear *int32 `json:"release_year"`
ReleaseSeason NullReleaseSeasonT `json:"release_season"`
ReleaseSeason *ReleaseSeasonT `json:"release_season"`
Season *int32 `json:"season"`
EpisodesAired *int32 `json:"episodes_aired"`
EpisodesAll *int32 `json:"episodes_all"`
@ -255,6 +280,6 @@ type Usertitle struct {
TitleID int64 `json:"title_id"`
Status UsertitleStatusT `json:"status"`
Rate *int32 `json:"rate"`
ReviewText *string `json:"review_text"`
ReviewDate pgtype.Timestamptz `json:"review_date"`
ReviewID *int64 `json:"review_id"`
Ctime pgtype.Timestamptz `json:"ctime"`
}

View file

@ -8,6 +8,8 @@ package sqlc
import (
"context"
"time"
"github.com/jackc/pgx/v5/pgtype"
)
const createImage = `-- name: CreateImage :one
@ -31,16 +33,166 @@ func (q *Queries) CreateImage(ctx context.Context, arg CreateImageParams) (Image
const getImageByID = `-- name: GetImageByID :one
SELECT id, storage_type, image_path
FROM images
WHERE id = $1
WHERE id = $1::bigint
`
func (q *Queries) GetImageByID(ctx context.Context, id int64) (Image, error) {
row := q.db.QueryRow(ctx, getImageByID, id)
func (q *Queries) GetImageByID(ctx context.Context, illustID int64) (Image, error) {
row := q.db.QueryRow(ctx, getImageByID, illustID)
var i Image
err := row.Scan(&i.ID, &i.StorageType, &i.ImagePath)
return i, err
}
const getReviewByID = `-- name: GetReviewByID :one
SELECT id, data, rating, user_id, title_id, created_at
FROM reviews
WHERE review_id = $1::bigint
`
// 100 is default limit
// -- name: ListTitles :many
// SELECT title_id, title_names, studio_id, poster_id, signal_ids,
//
// title_status, rating, rating_count, release_year, release_season,
// season, episodes_aired, episodes_all, episodes_len
//
// FROM titles
// ORDER BY title_id
// LIMIT $1 OFFSET $2;
// -- name: UpdateTitle :one
// UPDATE titles
// SET
//
// title_names = COALESCE(sqlc.narg('title_names'), title_names),
// studio_id = COALESCE(sqlc.narg('studio_id'), studio_id),
// poster_id = COALESCE(sqlc.narg('poster_id'), poster_id),
// signal_ids = COALESCE(sqlc.narg('signal_ids'), signal_ids),
// title_status = COALESCE(sqlc.narg('title_status'), title_status),
// release_year = COALESCE(sqlc.narg('release_year'), release_year),
// release_season = COALESCE(sqlc.narg('release_season'), release_season),
// episodes_aired = COALESCE(sqlc.narg('episodes_aired'), episodes_aired),
// episodes_all = COALESCE(sqlc.narg('episodes_all'), episodes_all),
// episodes_len = COALESCE(sqlc.narg('episodes_len'), episodes_len)
//
// WHERE title_id = sqlc.arg('title_id')
// RETURNING *;
func (q *Queries) GetReviewByID(ctx context.Context, reviewID int64) (Review, error) {
row := q.db.QueryRow(ctx, getReviewByID, reviewID)
var i Review
err := row.Scan(
&i.ID,
&i.Data,
&i.Rating,
&i.UserID,
&i.TitleID,
&i.CreatedAt,
)
return i, err
}
const getStudioByID = `-- name: GetStudioByID :one
SELECT id, studio_name, illust_id, studio_desc
FROM studios
WHERE id = $1::bigint
`
func (q *Queries) GetStudioByID(ctx context.Context, studioID int64) (Studio, error) {
row := q.db.QueryRow(ctx, getStudioByID, studioID)
var i Studio
err := row.Scan(
&i.ID,
&i.StudioName,
&i.IllustID,
&i.StudioDesc,
)
return i, err
}
const getTitleByID = `-- name: GetTitleByID :one
SELECT id, title_names, studio_id, poster_id, title_status, rating, rating_count, release_year, release_season, season, episodes_aired, episodes_all, episodes_len
FROM titles
WHERE id = $1::bigint
`
// -- name: ListUsers :many
// SELECT user_id, avatar_id, passhash, mail, nickname, disp_name, user_desc, creation_date
// FROM users
// ORDER BY user_id
// LIMIT $1 OFFSET $2;
// -- name: CreateUser :one
// INSERT INTO users (avatar_id, passhash, mail, nickname, disp_name, user_desc, creation_date)
// VALUES ($1, $2, $3, $4, $5, $6, $7)
// RETURNING user_id, avatar_id, nickname, disp_name, user_desc, creation_date;
// -- name: UpdateUser :one
// UPDATE users
// SET
//
// avatar_id = COALESCE(sqlc.narg('avatar_id'), avatar_id),
// disp_name = COALESCE(sqlc.narg('disp_name'), disp_name),
// user_desc = COALESCE(sqlc.narg('user_desc'), user_desc),
// passhash = COALESCE(sqlc.narg('passhash'), passhash)
//
// WHERE user_id = sqlc.arg('user_id')
// RETURNING user_id, avatar_id, nickname, disp_name, user_desc, creation_date;
// -- name: DeleteUser :exec
// DELETE FROM users
// WHERE user_id = $1;
func (q *Queries) GetTitleByID(ctx context.Context, titleID int64) (Title, error) {
row := q.db.QueryRow(ctx, getTitleByID, titleID)
var i Title
err := row.Scan(
&i.ID,
&i.TitleNames,
&i.StudioID,
&i.PosterID,
&i.TitleStatus,
&i.Rating,
&i.RatingCount,
&i.ReleaseYear,
&i.ReleaseSeason,
&i.Season,
&i.EpisodesAired,
&i.EpisodesAll,
&i.EpisodesLen,
)
return i, err
}
const getTitleTags = `-- name: GetTitleTags :many
SELECT
tag_names
FROM tags as g
JOIN title_tags as t ON(t.tag_id = g.id)
WHERE t.title_id = $1::bigint
`
func (q *Queries) GetTitleTags(ctx context.Context, titleID int64) ([][]byte, error) {
rows, err := q.db.Query(ctx, getTitleTags, titleID)
if err != nil {
return nil, err
}
defer rows.Close()
var items [][]byte
for rows.Next() {
var tag_names []byte
if err := rows.Scan(&tag_names); err != nil {
return nil, err
}
items = append(items, tag_names)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const getUserByID = `-- name: GetUserByID :one
SELECT id, avatar_id, mail, nickname, disp_name, user_desc, creation_date
FROM users
@ -71,3 +223,292 @@ func (q *Queries) GetUserByID(ctx context.Context, id int64) (GetUserByIDRow, er
)
return i, err
}
const insertStudio = `-- name: InsertStudio :one
INSERT INTO studios (studio_name, illust_id, studio_desc)
VALUES (
$1::text,
$2::bigint,
$3::text)
RETURNING id, studio_name, illust_id, studio_desc
`
type InsertStudioParams struct {
StudioName string `json:"studio_name"`
IllustID *int64 `json:"illust_id"`
StudioDesc *string `json:"studio_desc"`
}
func (q *Queries) InsertStudio(ctx context.Context, arg InsertStudioParams) (Studio, error) {
row := q.db.QueryRow(ctx, insertStudio, arg.StudioName, arg.IllustID, arg.StudioDesc)
var i Studio
err := row.Scan(
&i.ID,
&i.StudioName,
&i.IllustID,
&i.StudioDesc,
)
return i, err
}
const insertTag = `-- name: InsertTag :one
INSERT INTO tags (tag_names)
VALUES (
$1::jsonb)
RETURNING id, tag_names
`
func (q *Queries) InsertTag(ctx context.Context, tagNames []byte) (Tag, error) {
row := q.db.QueryRow(ctx, insertTag, tagNames)
var i Tag
err := row.Scan(&i.ID, &i.TagNames)
return i, err
}
const insertTitleTags = `-- name: InsertTitleTags :one
INSERT INTO title_tags (title_id, tag_id)
VALUES (
$1::bigint,
$2::bigint)
RETURNING title_id, tag_id
`
type InsertTitleTagsParams struct {
TitleID int64 `json:"title_id"`
TagID int64 `json:"tag_id"`
}
func (q *Queries) InsertTitleTags(ctx context.Context, arg InsertTitleTagsParams) (TitleTag, error) {
row := q.db.QueryRow(ctx, insertTitleTags, arg.TitleID, arg.TagID)
var i TitleTag
err := row.Scan(&i.TitleID, &i.TagID)
return i, err
}
const searchTitles = `-- name: SearchTitles :many
SELECT
id, title_names, studio_id, poster_id, title_status, rating, rating_count, release_year, release_season, season, episodes_aired, episodes_all, episodes_len
FROM titles
WHERE
CASE
WHEN $1::text IS NOT NULL THEN
(
SELECT bool_and(
EXISTS (
SELECT 1
FROM jsonb_each_text(title_names) AS t(key, val)
WHERE val ILIKE pattern
)
)
FROM unnest(
ARRAY(
SELECT '%' || trim(w) || '%'
FROM unnest(string_to_array($1::text, ' ')) AS w
WHERE trim(w) <> ''
)
) AS pattern
)
ELSE true
END
AND ($2::title_status_t IS NULL OR title_status = $2::title_status_t)
AND ($3::float IS NULL OR rating >= $3::float)
AND ($4::int IS NULL OR release_year = $4::int)
AND ($5::release_season_t IS NULL OR release_season = $5::release_season_t)
ORDER BY
-- Основной ключ: выбранное поле
CASE
WHEN $6::boolean AND $7::text = 'id' THEN id
WHEN $6::boolean AND $7::text = 'year' THEN release_year
WHEN $6::boolean AND $7::text = 'rating' THEN rating
-- WHEN sqlc.arg(forward)::boolean AND sqlc.arg(sort_by)::text = 'views' THEN views
END ASC,
CASE
WHEN NOT $6::boolean AND $7::text = 'id' THEN id
WHEN NOT $6::boolean AND $7::text = 'year' THEN release_year
WHEN NOT $6::boolean AND $7::text = 'rating' THEN rating
-- WHEN NOT sqlc.arg(forward)::boolean AND sqlc.arg(sort_by)::text = 'views' THEN views
END DESC,
-- Вторичный ключ: id только если НЕ сортируем по id
CASE
WHEN $7::text != 'id' AND $6::boolean THEN id
END ASC,
CASE
WHEN $7::text != 'id' AND NOT $6::boolean THEN id
END DESC
LIMIT COALESCE($8::int, 100)
`
type SearchTitlesParams struct {
Word *string `json:"word"`
Status *TitleStatusT `json:"status"`
Rating *float64 `json:"rating"`
ReleaseYear *int32 `json:"release_year"`
ReleaseSeason *ReleaseSeasonT `json:"release_season"`
Forward bool `json:"forward"`
SortBy string `json:"sort_by"`
Limit *int32 `json:"limit"`
}
func (q *Queries) SearchTitles(ctx context.Context, arg SearchTitlesParams) ([]Title, error) {
rows, err := q.db.Query(ctx, searchTitles,
arg.Word,
arg.Status,
arg.Rating,
arg.ReleaseYear,
arg.ReleaseSeason,
arg.Forward,
arg.SortBy,
arg.Limit,
)
if err != nil {
return nil, err
}
defer rows.Close()
var items []Title
for rows.Next() {
var i Title
if err := rows.Scan(
&i.ID,
&i.TitleNames,
&i.StudioID,
&i.PosterID,
&i.TitleStatus,
&i.Rating,
&i.RatingCount,
&i.ReleaseYear,
&i.ReleaseSeason,
&i.Season,
&i.EpisodesAired,
&i.EpisodesAll,
&i.EpisodesLen,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const searchUserTitles = `-- name: SearchUserTitles :many
SELECT
user_id, title_id, status, rate, review_id, ctime, id, title_names, studio_id, poster_id, title_status, rating, rating_count, release_year, release_season, season, episodes_aired, episodes_all, episodes_len
FROM usertitles as u
JOIN titles as t ON (u.title_id = t.id)
WHERE
CASE
WHEN $1::text IS NOT NULL THEN
(
SELECT bool_and(
EXISTS (
SELECT 1
FROM jsonb_each_text(t.title_names) AS t(key, val)
WHERE val ILIKE pattern
)
)
FROM unnest(
ARRAY(
SELECT '%' || trim(w) || '%'
FROM unnest(string_to_array($1::text, ' ')) AS w
WHERE trim(w) <> ''
)
) AS pattern
)
ELSE true
END
AND ($2::title_status_t IS NULL OR t.title_status = $2::title_status_t)
AND ($3::float IS NULL OR t.rating >= $3::float)
AND ($4::int IS NULL OR t.release_year = $4::int)
AND ($5::release_season_t IS NULL OR t.release_season = $5::release_season_t)
AND ($6::usertitle_status_t IS NULL OR u.usertitle_status = $6::usertitle_status_t)
LIMIT COALESCE($7::int, 100)
`
type SearchUserTitlesParams struct {
Word *string `json:"word"`
Status *TitleStatusT `json:"status"`
Rating *float64 `json:"rating"`
ReleaseYear *int32 `json:"release_year"`
ReleaseSeason *ReleaseSeasonT `json:"release_season"`
UsertitleStatus NullUsertitleStatusT `json:"usertitle_status"`
Limit *int32 `json:"limit"`
}
type SearchUserTitlesRow struct {
UserID int64 `json:"user_id"`
TitleID int64 `json:"title_id"`
Status UsertitleStatusT `json:"status"`
Rate *int32 `json:"rate"`
ReviewID *int64 `json:"review_id"`
Ctime pgtype.Timestamptz `json:"ctime"`
ID int64 `json:"id"`
TitleNames []byte `json:"title_names"`
StudioID int64 `json:"studio_id"`
PosterID *int64 `json:"poster_id"`
TitleStatus TitleStatusT `json:"title_status"`
Rating *float64 `json:"rating"`
RatingCount *int32 `json:"rating_count"`
ReleaseYear *int32 `json:"release_year"`
ReleaseSeason *ReleaseSeasonT `json:"release_season"`
Season *int32 `json:"season"`
EpisodesAired *int32 `json:"episodes_aired"`
EpisodesAll *int32 `json:"episodes_all"`
EpisodesLen []byte `json:"episodes_len"`
}
// 100 is default limit
// OFFSET sqlc.narg('offset')::int;
func (q *Queries) SearchUserTitles(ctx context.Context, arg SearchUserTitlesParams) ([]SearchUserTitlesRow, error) {
rows, err := q.db.Query(ctx, searchUserTitles,
arg.Word,
arg.Status,
arg.Rating,
arg.ReleaseYear,
arg.ReleaseSeason,
arg.UsertitleStatus,
arg.Limit,
)
if err != nil {
return nil, err
}
defer rows.Close()
var items []SearchUserTitlesRow
for rows.Next() {
var i SearchUserTitlesRow
if err := rows.Scan(
&i.UserID,
&i.TitleID,
&i.Status,
&i.Rate,
&i.ReviewID,
&i.Ctime,
&i.ID,
&i.TitleNames,
&i.StudioID,
&i.PosterID,
&i.TitleStatus,
&i.Rating,
&i.RatingCount,
&i.ReleaseYear,
&i.ReleaseSeason,
&i.Season,
&i.EpisodesAired,
&i.EpisodesAll,
&i.EpisodesLen,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}

View file

@ -25,3 +25,13 @@ sql:
go_type:
import: "time"
type: "Time"
- db_type: "title_status_t"
nullable: true
go_type:
pointer: true
type: "TitleStatusT"
- db_type: "release_season_t"
nullable: true
go_type:
pointer: true
type: "ReleaseSeasonT"