コミットを比較
4 コミット
main
...
ba960de76f
| 作成者 | SHA1 | 日付 | |
|---|---|---|---|
| ba960de76f | |||
| 8dc8cdf7f5 | |||
| ff5e8c4d49 | |||
| 638dccad6d |
@@ -1,4 +1,7 @@
|
|||||||
class ApplicationController < ActionController::API
|
class ApplicationController < ActionController::API
|
||||||
|
rescue_from ActiveRecord::RecordInvalid, with: :render_record_invalid
|
||||||
|
rescue_from ActiveRecord::RecordNotUnique, with: :render_record_not_unique
|
||||||
|
|
||||||
before_action :reject_banned_ip_address!
|
before_action :reject_banned_ip_address!
|
||||||
before_action :authenticate_user
|
before_action :authenticate_user
|
||||||
before_action :reject_banned_user!
|
before_action :reject_banned_user!
|
||||||
@@ -25,6 +28,29 @@ class ApplicationController < ActionController::API
|
|||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def render_bad_request message = 'リクエストが不正です.', field: nil, code: :bad_request
|
||||||
|
render_error(:bad_request, message, field:, code:)
|
||||||
|
end
|
||||||
|
|
||||||
|
def render_unprocessable_entity message = '入力を確認してください.', field: nil, code: :invalid
|
||||||
|
render_error(:unprocessable_entity, message, field:, code:)
|
||||||
|
end
|
||||||
|
|
||||||
|
def render_error status, message, field: nil, code: status
|
||||||
|
error = { code: code.to_s, message: }
|
||||||
|
error[:field] = field.to_s if field.present?
|
||||||
|
|
||||||
|
render json: { errors: [error] }, status:
|
||||||
|
end
|
||||||
|
|
||||||
|
def render_record_invalid error
|
||||||
|
render_validation_error error.record
|
||||||
|
end
|
||||||
|
|
||||||
|
def render_record_not_unique _error = nil
|
||||||
|
render_validation_error base: ['すでに存在してゐます.']
|
||||||
|
end
|
||||||
|
|
||||||
def reject_banned_ip_address!
|
def reject_banned_ip_address!
|
||||||
ip_address = IpAddress.find_by(ip_address: IPAddr.new(request.remote_ip).hton)
|
ip_address = IpAddress.find_by(ip_address: IPAddr.new(request.remote_ip).hton)
|
||||||
return unless ip_address&.banned?
|
return unless ip_address&.banned?
|
||||||
@@ -37,4 +63,28 @@ class ApplicationController < ActionController::API
|
|||||||
|
|
||||||
head :forbidden
|
head :forbidden
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def render_validation_error record = nil, fields: { }, base: [], status: :unprocessable_entity
|
||||||
|
errors = { }
|
||||||
|
|
||||||
|
if record
|
||||||
|
record.errors.each do |error|
|
||||||
|
errors[error.attribute] ||= []
|
||||||
|
errors[error.attribute] << error.message
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
fields.each do |attr, messages|
|
||||||
|
errors[attr.to_sym] ||= []
|
||||||
|
errors[attr.to_sym].concat(Array(messages))
|
||||||
|
end
|
||||||
|
|
||||||
|
base_errors = Array(base) + Array(errors.delete(:base))
|
||||||
|
|
||||||
|
render json: { type: 'validation_error',
|
||||||
|
message: '入力内容を確認してください.',
|
||||||
|
errors:,
|
||||||
|
base_errors: },
|
||||||
|
status:
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -2,7 +2,8 @@ class DeerjikistsController < ApplicationController
|
|||||||
def show
|
def show
|
||||||
platform = params[:platform].to_s.strip
|
platform = params[:platform].to_s.strip
|
||||||
code = params[:code].to_s.strip
|
code = params[:code].to_s.strip
|
||||||
return head :bad_request if platform.blank? || code.blank?
|
return render_bad_request('platform は必須です.', field: :platform) if platform.blank?
|
||||||
|
return render_bad_request('code は必須です.', field: :code) if code.blank?
|
||||||
|
|
||||||
deerjikist = Deerjikist
|
deerjikist = Deerjikist
|
||||||
.joins(:tag)
|
.joins(:tag)
|
||||||
@@ -22,7 +23,9 @@ class DeerjikistsController < ApplicationController
|
|||||||
platform = params[:platform].to_s.strip
|
platform = params[:platform].to_s.strip
|
||||||
code = params[:code].to_s.strip
|
code = params[:code].to_s.strip
|
||||||
tag_id = params[:tag_id].to_i
|
tag_id = params[:tag_id].to_i
|
||||||
return head :bad_request if platform.blank? || code.blank? || tag_id <= 0
|
return render_bad_request('platform は必須です.', field: :platform) if platform.blank?
|
||||||
|
return render_bad_request('code は必須です.', field: :code) if code.blank?
|
||||||
|
return render_bad_request('tag_id が不正です.', field: :tag_id) if tag_id <= 0
|
||||||
|
|
||||||
deerjikist = Deerjikist.find_or_initialize_by(platform:, code:).tap do |d|
|
deerjikist = Deerjikist.find_or_initialize_by(platform:, code:).tap do |d|
|
||||||
d.tag_id = tag_id
|
d.tag_id = tag_id
|
||||||
@@ -38,7 +41,8 @@ class DeerjikistsController < ApplicationController
|
|||||||
|
|
||||||
platform = params[:platform].to_s.strip
|
platform = params[:platform].to_s.strip
|
||||||
code = params[:code].to_s.strip
|
code = params[:code].to_s.strip
|
||||||
return head :bad_request if platform.blank? || code.blank?
|
return render_bad_request('platform は必須です.', field: :platform) if platform.blank?
|
||||||
|
return render_bad_request('code は必須です.', field: :code) if code.blank?
|
||||||
|
|
||||||
Deerjikist.find([platform, code]).destroy!
|
Deerjikist.find([platform, code]).destroy!
|
||||||
|
|
||||||
|
|||||||
@@ -40,7 +40,8 @@ class MaterialsController < ApplicationController
|
|||||||
tag_name_raw = params[:tag].to_s.strip
|
tag_name_raw = params[:tag].to_s.strip
|
||||||
file = params[:file]
|
file = params[:file]
|
||||||
url = params[:url].to_s.strip.presence
|
url = params[:url].to_s.strip.presence
|
||||||
return head :bad_request if tag_name_raw.blank? || (file.blank? && url.blank?)
|
return render_bad_request('タグは必須です.', field: :tag) if tag_name_raw.blank?
|
||||||
|
return render_bad_request('ファイルまたは URL は必須です.') if file.blank? && url.blank?
|
||||||
|
|
||||||
tag_name = TagName.find_undiscard_or_create_by!(name: tag_name_raw)
|
tag_name = TagName.find_undiscard_or_create_by!(name: tag_name_raw)
|
||||||
tag = tag_name.tag
|
tag = tag_name.tag
|
||||||
@@ -54,7 +55,7 @@ class MaterialsController < ApplicationController
|
|||||||
if material.save
|
if material.save
|
||||||
render json: MaterialRepr.base(material, host: request.base_url), status: :created
|
render json: MaterialRepr.base(material, host: request.base_url), status: :created
|
||||||
else
|
else
|
||||||
render json: { errors: material.errors.full_messages }, status: :unprocessable_entity
|
render_model_errors(material)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -68,7 +69,8 @@ class MaterialsController < ApplicationController
|
|||||||
tag_name_raw = params[:tag].to_s.strip
|
tag_name_raw = params[:tag].to_s.strip
|
||||||
file = params[:file]
|
file = params[:file]
|
||||||
url = params[:url].to_s.strip.presence
|
url = params[:url].to_s.strip.presence
|
||||||
return head :bad_request if tag_name_raw.blank? || (file.blank? && url.blank?)
|
return render_bad_request('タグは必須です.', field: :tag) if tag_name_raw.blank?
|
||||||
|
return render_bad_request('ファイルまたは URL は必須です.') if file.blank? && url.blank?
|
||||||
|
|
||||||
tag_name = TagName.find_undiscard_or_create_by!(name: tag_name_raw)
|
tag_name = TagName.find_undiscard_or_create_by!(name: tag_name_raw)
|
||||||
tag = tag_name.tag
|
tag = tag_name.tag
|
||||||
@@ -84,7 +86,7 @@ class MaterialsController < ApplicationController
|
|||||||
if material.save
|
if material.save
|
||||||
render json: MaterialRepr.base(material, host: request.base_url)
|
render json: MaterialRepr.base(material, host: request.base_url)
|
||||||
else
|
else
|
||||||
render json: { errors: material.errors.full_messages }, status: :unprocessable_entity
|
render_model_errors(material)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|||||||
@@ -30,12 +30,14 @@ class NicoTagsController < ApplicationController
|
|||||||
id = params[:id].to_i
|
id = params[:id].to_i
|
||||||
|
|
||||||
tag = Tag.find(id)
|
tag = Tag.find(id)
|
||||||
return head :bad_request unless tag.nico?
|
return render_bad_request('ニコニコ・タグを指定してください.', field: :id) unless tag.nico?
|
||||||
|
|
||||||
linked_tag_names = params[:tags].to_s.split
|
linked_tag_names = params[:tags].to_s.split
|
||||||
linked_tags = Tag.normalise_tags!(linked_tag_names, with_tagme: false,
|
linked_tags = Tag.normalise_tags!(linked_tag_names, with_tagme: false,
|
||||||
with_no_deerjikist: false)
|
with_no_deerjikist: false)
|
||||||
return head :bad_request if linked_tags.any? { |t| t.nico? }
|
if linked_tags.any? { |t| t.nico? }
|
||||||
|
return render_bad_request('ニコニコ・タグ同士は連携できません.', field: :tags)
|
||||||
|
end
|
||||||
|
|
||||||
ApplicationRecord.transaction do
|
ApplicationRecord.transaction do
|
||||||
TagVersioning.record_tag_snapshots!(linked_tags, created_by_user: current_user)
|
TagVersioning.record_tag_snapshots!(linked_tags, created_by_user: current_user)
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ class PostsController < ApplicationController
|
|||||||
filtered_posts
|
filtered_posts
|
||||||
.joins("LEFT JOIN (#{ pt_max_sql }) pt_max ON pt_max.post_id = posts.id")
|
.joins("LEFT JOIN (#{ pt_max_sql }) pt_max ON pt_max.post_id = posts.id")
|
||||||
.reselect('posts.*', Arel.sql("#{ updated_at_all_sql } AS updated_at_all"))
|
.reselect('posts.*', Arel.sql("#{ updated_at_all_sql } AS updated_at_all"))
|
||||||
.preload(tags: [:deerjikists, :materials, { tag_name: :wiki_page }])
|
.preload(:uploaded_user, tags: [:deerjikists, :materials, { tag_name: :wiki_page }])
|
||||||
.with_attached_thumbnail
|
.with_attached_thumbnail
|
||||||
|
|
||||||
q = q.where('posts.url LIKE ?', "%#{ url }%") if url
|
q = q.where('posts.url LIKE ?', "%#{ url }%") if url
|
||||||
@@ -95,7 +95,9 @@ class PostsController < ApplicationController
|
|||||||
end
|
end
|
||||||
|
|
||||||
def random
|
def random
|
||||||
post = filtered_posts.preload(tags: [:deerjikists, :materials, { tag_name: :wiki_page }])
|
post = filtered_posts.preload(:uploaded_user,
|
||||||
|
tags: [:deerjikists, :materials, { tag_name: :wiki_page }])
|
||||||
|
.with_attached_thumbnail
|
||||||
.order('RAND()')
|
.order('RAND()')
|
||||||
.first
|
.first
|
||||||
return head :not_found unless post
|
return head :not_found unless post
|
||||||
@@ -104,12 +106,24 @@ class PostsController < ApplicationController
|
|||||||
end
|
end
|
||||||
|
|
||||||
def show
|
def show
|
||||||
post = Post.includes(tags: [:deerjikists, :materials, { tag_name: :wiki_page }]).find_by(id: params[:id])
|
post =
|
||||||
|
Post
|
||||||
|
.includes(:uploaded_user, tags: [:deerjikists, :materials, { tag_name: :wiki_page }])
|
||||||
|
.with_attached_thumbnail
|
||||||
|
.find_by(id: params[:id])
|
||||||
return head :not_found unless post
|
return head :not_found unless post
|
||||||
|
|
||||||
render json: PostRepr.base(post, current_user)
|
parent_posts = post.parents.with_attached_thumbnail.order(:id).to_a
|
||||||
.merge(tags: build_tag_tree_for(post.tags),
|
child_posts = post.children.with_attached_thumbnail.order(:id).to_a
|
||||||
related: PostRepr.many(post.related(limit: 20)))
|
sibling_posts = sibling_posts_by_parent(parent_posts.map(&:id))
|
||||||
|
related = post.related(limit: 20).to_a
|
||||||
|
|
||||||
|
render json: PostRepr.detail(post, current_user,
|
||||||
|
parent_posts:,
|
||||||
|
child_posts:,
|
||||||
|
sibling_posts:,
|
||||||
|
related:)
|
||||||
|
.merge(tags: build_tag_tree_for(post.tags))
|
||||||
end
|
end
|
||||||
|
|
||||||
def create
|
def create
|
||||||
@@ -148,11 +162,11 @@ class PostsController < ApplicationController
|
|||||||
post.reload
|
post.reload
|
||||||
render json: PostRepr.base(post), status: :created
|
render json: PostRepr.base(post), status: :created
|
||||||
rescue Tag::NicoTagNormalisationError
|
rescue Tag::NicoTagNormalisationError
|
||||||
head :bad_request
|
render_validation_error fields: { tags: 'ニコニコ・タグは直接指定できません.' }
|
||||||
rescue ArgumentError => e
|
rescue ArgumentError => e
|
||||||
render json: { errors: [e.message] }, status: :unprocessable_entity
|
render_validation_error fields: { parent_post_ids: [e.message] }
|
||||||
rescue ActiveRecord::RecordInvalid => e
|
rescue ActiveRecord::RecordInvalid => e
|
||||||
render json: { errors: e.record.errors.full_messages }, status: :unprocessable_entity
|
render_post_form_record_invalid e.record
|
||||||
end
|
end
|
||||||
|
|
||||||
def viewed
|
def viewed
|
||||||
@@ -175,10 +189,10 @@ class PostsController < ApplicationController
|
|||||||
|
|
||||||
force = bool?(:force)
|
force = bool?(:force)
|
||||||
merge = bool?(:merge)
|
merge = bool?(:merge)
|
||||||
return head :bad_request if force && merge
|
return render_bad_request('force と merge は同時に指定できません.') if force && merge
|
||||||
|
|
||||||
base_version_no = parse_base_version_no
|
base_version_no = parse_base_version_no
|
||||||
return head :bad_request if !(force) && !(base_version_no)
|
return render_bad_request('base_version_no は必須です.', field: :base_version_no) if !(force) && !(base_version_no)
|
||||||
|
|
||||||
title = params[:title].presence
|
title = params[:title].presence
|
||||||
tag_names = params[:tags].to_s.split
|
tag_names = params[:tags].to_s.split
|
||||||
@@ -238,11 +252,11 @@ class PostsController < ApplicationController
|
|||||||
json['tags'] = build_tag_tree_for(post.tags)
|
json['tags'] = build_tag_tree_for(post.tags)
|
||||||
render json:, status: :ok
|
render json:, status: :ok
|
||||||
rescue Tag::NicoTagNormalisationError
|
rescue Tag::NicoTagNormalisationError
|
||||||
head :bad_request
|
render_validation_error fields: { tags: ['ニコニコ・タグは直接指定できません.'] }
|
||||||
rescue ArgumentError => e
|
rescue ArgumentError => e
|
||||||
render json: { errors: [e.message] }, status: :unprocessable_entity
|
render_validation_error fields: { parent_post_ids: [e.message] }
|
||||||
rescue ActiveRecord::RecordInvalid => e
|
rescue ActiveRecord::RecordInvalid => e
|
||||||
render json: { errors: e.record.errors.full_messages }, status: :unprocessable_entity
|
render_post_form_record_invalid e.record
|
||||||
end
|
end
|
||||||
|
|
||||||
def changes
|
def changes
|
||||||
@@ -385,7 +399,7 @@ class PostsController < ApplicationController
|
|||||||
return nil unless tag
|
return nil unless tag
|
||||||
|
|
||||||
if path.include?(tag_id)
|
if path.include?(tag_id)
|
||||||
return TagRepr.base(tag).merge(children: [])
|
return TagRepr.inline(tag).merge(children: [])
|
||||||
end
|
end
|
||||||
|
|
||||||
if memo.key?(tag_id)
|
if memo.key?(tag_id)
|
||||||
@@ -397,12 +411,26 @@ class PostsController < ApplicationController
|
|||||||
|
|
||||||
children = child_ids.filter_map { |cid| build_node.(cid, new_path) }
|
children = child_ids.filter_map { |cid| build_node.(cid, new_path) }
|
||||||
|
|
||||||
memo[tag_id] = TagRepr.base(tag).merge(children:)
|
memo[tag_id] = TagRepr.inline(tag).merge(children:)
|
||||||
end
|
end
|
||||||
|
|
||||||
root_ids.filter_map { |id| build_node.call(id, []) }
|
root_ids.filter_map { |id| build_node.call(id, []) }
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def sibling_posts_by_parent parent_post_ids
|
||||||
|
return { } if parent_post_ids.blank?
|
||||||
|
|
||||||
|
implications =
|
||||||
|
PostImplication
|
||||||
|
.where(parent_post_id: parent_post_ids)
|
||||||
|
.includes(post: { thumbnail_attachment: :blob })
|
||||||
|
.order(:parent_post_id, :post_id)
|
||||||
|
|
||||||
|
implications.group_by(&:parent_post_id).transform_values { |items|
|
||||||
|
items.map(&:post)
|
||||||
|
}
|
||||||
|
end
|
||||||
|
|
||||||
def parse_parent_post_ids
|
def parse_parent_post_ids
|
||||||
raise ArgumentError, 'parent_post_ids は必須です.' unless params.key?(:parent_post_ids)
|
raise ArgumentError, 'parent_post_ids は必須です.' unless params.key?(:parent_post_ids)
|
||||||
|
|
||||||
@@ -416,7 +444,7 @@ class PostsController < ApplicationController
|
|||||||
|
|
||||||
def sync_parent_posts! post, parent_post_ids
|
def sync_parent_posts! post, parent_post_ids
|
||||||
if parent_post_ids.include?(post.id)
|
if parent_post_ids.include?(post.id)
|
||||||
post.errors.add(:base, '自分自身を親投稿にはできません.')
|
post.errors.add :parent_post_ids, '自分自身を親投稿にはできません.'
|
||||||
raise ActiveRecord::RecordInvalid, post
|
raise ActiveRecord::RecordInvalid, post
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -424,7 +452,8 @@ class PostsController < ApplicationController
|
|||||||
missing_ids = parent_post_ids - existing_ids
|
missing_ids = parent_post_ids - existing_ids
|
||||||
|
|
||||||
if missing_ids.present?
|
if missing_ids.present?
|
||||||
post.errors.add(:base, "存在しない親投稿 ID があります: #{ missing_ids.join(' ') }")
|
post.errors.add :parent_post_ids,
|
||||||
|
"存在しない親投稿 ID があります: #{ missing_ids.join(' ') }"
|
||||||
raise ActiveRecord::RecordInvalid, post
|
raise ActiveRecord::RecordInvalid, post
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -640,4 +669,14 @@ class PostsController < ApplicationController
|
|||||||
|
|
||||||
merged.uniq.sort
|
merged.uniq.sort
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def render_post_form_record_invalid record
|
||||||
|
if e.record.is_a?(TagName) || e.record.is_a?(Tag)
|
||||||
|
render_validation_error(fields: { tags: e.record.errors.full_messages.map { |message|
|
||||||
|
"タグ名 “#{ e.record.name }”: #{ message }"
|
||||||
|
} })
|
||||||
|
else
|
||||||
|
render_validation_error(record)
|
||||||
|
end
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ class PreviewController < ApplicationController
|
|||||||
return head :unauthorized unless current_user
|
return head :unauthorized unless current_user
|
||||||
|
|
||||||
url = params[:url]
|
url = params[:url]
|
||||||
return head :bad_request unless url.present?
|
return render_bad_request('URL は必須です.', field: :url) unless url.present?
|
||||||
|
|
||||||
unless url.start_with?(/http(s)?:\/\//)
|
unless url.start_with?(/http(s)?:\/\//)
|
||||||
url = 'http://' + url
|
url = 'http://' + url
|
||||||
@@ -16,7 +16,7 @@ class PreviewController < ApplicationController
|
|||||||
|
|
||||||
render json: { title: title }
|
render json: { title: title }
|
||||||
rescue => e
|
rescue => e
|
||||||
render json: { error: e.message }, status: :bad_request
|
render_bad_request(e.message, field: :url)
|
||||||
end
|
end
|
||||||
|
|
||||||
def thumbnail
|
def thumbnail
|
||||||
@@ -25,7 +25,7 @@ class PreviewController < ApplicationController
|
|||||||
return head :unauthorized unless current_user
|
return head :unauthorized unless current_user
|
||||||
|
|
||||||
url = params[:url]
|
url = params[:url]
|
||||||
return head :bad_request if url.blank?
|
return render_bad_request('URL は必須です.', field: :url) if url.blank?
|
||||||
|
|
||||||
unless url.start_with?(/http(s)?:\/\//)
|
unless url.start_with?(/http(s)?:\/\//)
|
||||||
url = 'http://' + url
|
url = 'http://' + url
|
||||||
@@ -40,7 +40,8 @@ class PreviewController < ApplicationController
|
|||||||
File.delete(path) rescue nil
|
File.delete(path) rescue nil
|
||||||
send_file image.path, type: 'image/png', disposition: 'inline'
|
send_file image.path, type: 'image/png', disposition: 'inline'
|
||||||
else
|
else
|
||||||
render json: { error: 'Failed to generate thumbnail' }, status: :internal_server_error
|
render_error(:internal_server_error, 'サムネールを生成できませんでした.',
|
||||||
|
code: :thumbnail_generation_failed)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -5,11 +5,12 @@ class TagChildrenController < ApplicationController
|
|||||||
|
|
||||||
parent_id = params[:parent_id]
|
parent_id = params[:parent_id]
|
||||||
child_id = params[:child_id]
|
child_id = params[:child_id]
|
||||||
return head :bad_request if parent_id.blank? || child_id.blank?
|
return render_bad_request('parent_id は必須です.', field: :parent_id) if parent_id.blank?
|
||||||
|
return render_bad_request('child_id は必須です.', field: :child_id) if child_id.blank?
|
||||||
|
|
||||||
parent = Tag.find(parent_id)
|
parent = Tag.find(parent_id)
|
||||||
child = Tag.find(child_id)
|
child = Tag.find(child_id)
|
||||||
return head :bad_request if parent.nico? || child.nico?
|
return render_bad_request('ニコニコ・タグの階層は変更できません.') if parent.nico? || child.nico?
|
||||||
|
|
||||||
ApplicationRecord.transaction do
|
ApplicationRecord.transaction do
|
||||||
TagVersioning.ensure_snapshot!(child, created_by_user: current_user)
|
TagVersioning.ensure_snapshot!(child, created_by_user: current_user)
|
||||||
@@ -27,11 +28,12 @@ class TagChildrenController < ApplicationController
|
|||||||
|
|
||||||
parent_id = params[:parent_id]
|
parent_id = params[:parent_id]
|
||||||
child_id = params[:child_id]
|
child_id = params[:child_id]
|
||||||
return head :bad_request if parent_id.blank? || child_id.blank?
|
return render_bad_request('parent_id は必須です.', field: :parent_id) if parent_id.blank?
|
||||||
|
return render_bad_request('child_id は必須です.', field: :child_id) if child_id.blank?
|
||||||
|
|
||||||
parent = Tag.find(parent_id)
|
parent = Tag.find(parent_id)
|
||||||
child = Tag.find(child_id)
|
child = Tag.find(child_id)
|
||||||
return head :bad_request if parent.nico? || child.nico?
|
return render_bad_request('ニコニコ・タグの階層は変更できません.') if parent.nico? || child.nico?
|
||||||
|
|
||||||
ApplicationRecord.transaction do
|
ApplicationRecord.transaction do
|
||||||
TagVersioning.ensure_snapshot!(child, created_by_user: current_user)
|
TagVersioning.ensure_snapshot!(child, created_by_user: current_user)
|
||||||
|
|||||||
@@ -168,7 +168,7 @@ class TagsController < ApplicationController
|
|||||||
|
|
||||||
def show_by_name
|
def show_by_name
|
||||||
name = params[:name].to_s.strip
|
name = params[:name].to_s.strip
|
||||||
return head :bad_request if name.blank?
|
return render_bad_request('name は必須です.', field: :name) if name.blank?
|
||||||
|
|
||||||
tag = Tag.joins(:tag_name)
|
tag = Tag.joins(:tag_name)
|
||||||
.includes(:tag_name, :materials, tag_name: :wiki_page)
|
.includes(:tag_name, :materials, tag_name: :wiki_page)
|
||||||
@@ -192,7 +192,7 @@ class TagsController < ApplicationController
|
|||||||
|
|
||||||
def deerjikists_by_name
|
def deerjikists_by_name
|
||||||
name = params[:name].to_s.strip
|
name = params[:name].to_s.strip
|
||||||
return head :bad_request if name.blank?
|
return render_bad_request('name は必須です.', field: :name) if name.blank?
|
||||||
|
|
||||||
tag = Tag.joins(:tag_name)
|
tag = Tag.joins(:tag_name)
|
||||||
.includes(:tag_name, tag_name: :wiki_page)
|
.includes(:tag_name, tag_name: :wiki_page)
|
||||||
@@ -228,7 +228,7 @@ class TagsController < ApplicationController
|
|||||||
|
|
||||||
def materials_by_name
|
def materials_by_name
|
||||||
name = params[:name].to_s.strip
|
name = params[:name].to_s.strip
|
||||||
return head :bad_request if name.blank?
|
return render_bad_request('name は必須です.', field: :name) if name.blank?
|
||||||
|
|
||||||
tag = Tag.joins(:tag_name)
|
tag = Tag.joins(:tag_name)
|
||||||
.includes(:tag_name, :materials, tag_name: :wiki_page)
|
.includes(:tag_name, :materials, tag_name: :wiki_page)
|
||||||
@@ -247,17 +247,16 @@ class TagsController < ApplicationController
|
|||||||
|
|
||||||
name = params[:name].to_s.strip
|
name = params[:name].to_s.strip
|
||||||
category = params[:category].to_s.strip
|
category = params[:category].to_s.strip
|
||||||
return head :unprocessable_entity if name.blank? || category.blank?
|
return render_unprocessable_entity('名前は必須です.', field: :name) if name.blank?
|
||||||
|
return render_unprocessable_entity('カテゴリは必須です.', field: :category) if category.blank?
|
||||||
|
|
||||||
if name != tag.name &&
|
if name != tag.name &&
|
||||||
tag.in?([Tag.tagme, Tag.bot, Tag.no_deerjikist, Tag.video, Tag.niconico])
|
tag.in?([Tag.tagme, Tag.bot, Tag.no_deerjikist, Tag.video, Tag.niconico])
|
||||||
return render json: { error: 'システム・タグの名称は変更できません.' },
|
return render_unprocessable_entity('システム・タグの名称は変更できません.', field: :name)
|
||||||
status: :unprocessable_entity
|
|
||||||
end
|
end
|
||||||
|
|
||||||
if tag.nico? || category == 'nico'
|
if tag.nico? || category == 'nico'
|
||||||
return render json: { error: 'ニコタグは変更できません.' },
|
return render_unprocessable_entity('ニコタグは変更できません.', field: :category)
|
||||||
status: :unprocessable_entity
|
|
||||||
end
|
end
|
||||||
|
|
||||||
alias_names = params[:aliases].to_s.split.uniq
|
alias_names = params[:aliases].to_s.split.uniq
|
||||||
@@ -302,8 +301,7 @@ class TagsController < ApplicationController
|
|||||||
tag = Tag.find(params[:id])
|
tag = Tag.find(params[:id])
|
||||||
|
|
||||||
if tag.nico? || (category.present? && category == 'nico')
|
if tag.nico? || (category.present? && category == 'nico')
|
||||||
return render json: { error: 'ニコタグは変更できません.' },
|
return render_unprocessable_entity('ニコタグは変更できません.', field: :category)
|
||||||
status: :unprocessable_entity
|
|
||||||
end
|
end
|
||||||
|
|
||||||
ApplicationRecord.transaction do
|
ApplicationRecord.transaction do
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ class TheatreCommentsController < ApplicationController
|
|||||||
return head :unauthorized unless current_user
|
return head :unauthorized unless current_user
|
||||||
|
|
||||||
content = params[:content]
|
content = params[:content]
|
||||||
return head :unprocessable_entity if content.blank?
|
return render_unprocessable_entity('本文は必須です.', field: :content) if content.blank?
|
||||||
|
|
||||||
theatre = Theatre.find_by(id: params[:theatre_id])
|
theatre = Theatre.find_by(id: params[:theatre_id])
|
||||||
return head :not_found unless theatre
|
return head :not_found unless theatre
|
||||||
|
|||||||
@@ -42,12 +42,12 @@ class UsersController < ApplicationController
|
|||||||
return head :unauthorized if user&.id != params[:id].to_i
|
return head :unauthorized if user&.id != params[:id].to_i
|
||||||
|
|
||||||
name = params[:name]
|
name = params[:name]
|
||||||
return head :bad_request if name.blank?
|
return render_bad_request('名前は必須です.', field: :name) if name.blank?
|
||||||
|
|
||||||
if user.update(name:)
|
if user.update(name:)
|
||||||
render json: user.slice(:id, :name, :inheritance_code, :role), status: :ok
|
render json: user.slice(:id, :name, :inheritance_code, :role), status: :ok
|
||||||
else
|
else
|
||||||
render json: user.errors, status: :unprocessable_entity
|
render_model_errors(user)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ class WikiPagesController < ApplicationController
|
|||||||
|
|
||||||
def diff
|
def diff
|
||||||
id = params[:id]
|
id = params[:id]
|
||||||
return head :bad_request if id.blank?
|
return render_bad_request('id は必須です.', field: :id) if id.blank?
|
||||||
|
|
||||||
from = params[:from].presence
|
from = params[:from].presence
|
||||||
to = params[:to].presence
|
to = params[:to].presence
|
||||||
@@ -56,7 +56,7 @@ class WikiPagesController < ApplicationController
|
|||||||
from_rev = from && page.wiki_revisions.find(from)
|
from_rev = from && page.wiki_revisions.find(from)
|
||||||
to_rev = to ? page.wiki_revisions.find(to) : page.current_revision
|
to_rev = to ? page.wiki_revisions.find(to) : page.current_revision
|
||||||
if ((from_rev && !(from_rev.content?)) || !(to_rev&.content?))
|
if ((from_rev && !(from_rev.content?)) || !(to_rev&.content?))
|
||||||
return head :unprocessable_entity
|
return render_unprocessable_entity('差分を表示できない版です.')
|
||||||
end
|
end
|
||||||
|
|
||||||
diffs = Diff::LCS.sdiff(from_rev&.body&.lines || [], to_rev.body.lines)
|
diffs = Diff::LCS.sdiff(from_rev&.body&.lines || [], to_rev.body.lines)
|
||||||
@@ -89,7 +89,8 @@ class WikiPagesController < ApplicationController
|
|||||||
body = params[:body].to_s
|
body = params[:body].to_s
|
||||||
message = params[:message].presence
|
message = params[:message].presence
|
||||||
|
|
||||||
return head :unprocessable_entity if title.blank? || body.blank?
|
return render_unprocessable_entity('タイトルは必須です.', field: :title) if title.blank?
|
||||||
|
return render_unprocessable_entity('本文は必須です.', field: :body) if body.blank?
|
||||||
|
|
||||||
tag_name = TagName.find_undiscard_or_create_by!(name: title)
|
tag_name = TagName.find_undiscard_or_create_by!(name: title)
|
||||||
|
|
||||||
@@ -101,8 +102,10 @@ class WikiPagesController < ApplicationController
|
|||||||
message:)
|
message:)
|
||||||
|
|
||||||
render json: WikiPageRepr.base(page), status: :created
|
render json: WikiPageRepr.base(page), status: :created
|
||||||
rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotUnique
|
rescue ActiveRecord::RecordInvalid => e
|
||||||
head :unprocessable_entity
|
render_model_errors(e.record)
|
||||||
|
rescue ActiveRecord::RecordNotUnique
|
||||||
|
render_record_not_unique
|
||||||
end
|
end
|
||||||
|
|
||||||
def update
|
def update
|
||||||
@@ -112,7 +115,8 @@ class WikiPagesController < ApplicationController
|
|||||||
title = params[:title]&.strip
|
title = params[:title]&.strip
|
||||||
body = params[:body].to_s
|
body = params[:body].to_s
|
||||||
|
|
||||||
return head :unprocessable_entity if title.blank? || body.blank?
|
return render_unprocessable_entity('タイトルは必須です.', field: :title) if title.blank?
|
||||||
|
return render_unprocessable_entity('本文は必須です.', field: :body) if body.blank?
|
||||||
|
|
||||||
page = WikiPage.find(params[:id])
|
page = WikiPage.find(params[:id])
|
||||||
base_revision_id = params[:base_revision_id].presence
|
base_revision_id = params[:base_revision_id].presence
|
||||||
|
|||||||
@@ -94,7 +94,7 @@ class Post < ApplicationRecord
|
|||||||
return if !(f) || !(b)
|
return if !(f) || !(b)
|
||||||
|
|
||||||
if f >= b
|
if f >= b
|
||||||
errors.add :original_created_before, 'オリジナルの作成日時の順番がをかしぃです.'
|
errors.add :original_created_at, 'オリジナルの作成日時の順番がをかしぃです.'
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|||||||
@@ -2,20 +2,65 @@
|
|||||||
|
|
||||||
|
|
||||||
module PostRepr
|
module PostRepr
|
||||||
BASE = { include: { tags: TagRepr::BASE, uploaded_user: UserRepr::BASE },
|
BASE_FIELDS = [
|
||||||
methods: [:parent_posts, :child_posts, :sibling_posts] }.freeze
|
:id,
|
||||||
|
:version_no,
|
||||||
|
:url,
|
||||||
|
:title,
|
||||||
|
:thumbnail_base,
|
||||||
|
:original_created_from,
|
||||||
|
:original_created_before,
|
||||||
|
:created_at,
|
||||||
|
:updated_at
|
||||||
|
].freeze
|
||||||
|
|
||||||
module_function
|
module_function
|
||||||
|
|
||||||
def base post, current_user = nil
|
def base post, current_user = nil
|
||||||
json = post.as_json(BASE)
|
json = common(post)
|
||||||
return json.merge(viewed: false) unless current_user
|
json['tags'] = tag_json(post.tags)
|
||||||
|
json['uploaded_user'] = post.uploaded_user && UserRepr.base(post.uploaded_user)
|
||||||
|
json['viewed'] = current_user ? current_user.viewed?(post) : false
|
||||||
|
json
|
||||||
|
end
|
||||||
|
|
||||||
viewed = current_user.viewed?(post)
|
def detail post, current_user = nil, parent_posts: [], child_posts: [],
|
||||||
json.merge(viewed:)
|
sibling_posts: { }, related: []
|
||||||
|
base(post, current_user).merge(
|
||||||
|
'parent_posts' => cards(parent_posts),
|
||||||
|
'child_posts' => cards(child_posts),
|
||||||
|
'sibling_posts' => sibling_posts.transform_keys(&:to_s).transform_values { |posts|
|
||||||
|
cards(posts)
|
||||||
|
},
|
||||||
|
'related' => cards(related))
|
||||||
|
end
|
||||||
|
|
||||||
|
def card post
|
||||||
|
common(post).merge('parent_posts' => [], 'child_posts' => [])
|
||||||
|
end
|
||||||
|
|
||||||
|
def cards posts
|
||||||
|
posts.map { |post| card(post) }
|
||||||
end
|
end
|
||||||
|
|
||||||
def many posts, current_user = nil
|
def many posts, current_user = nil
|
||||||
posts.map { |p| base(p, current_user) }
|
posts.map { |p| base(p, current_user) }
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def common post
|
||||||
|
BASE_FIELDS.to_h { |field| [field.to_s, post.public_send(field)] }
|
||||||
|
.merge('thumbnail' => thumbnail_url(post))
|
||||||
|
end
|
||||||
|
|
||||||
|
def tag_json tags
|
||||||
|
tags.map { |tag| TagRepr.inline(tag) }
|
||||||
|
end
|
||||||
|
|
||||||
|
def thumbnail_url post
|
||||||
|
return nil unless post.thumbnail.attached?
|
||||||
|
|
||||||
|
Rails.application.routes.url_helpers.rails_blob_url(post.thumbnail, only_path: false)
|
||||||
|
rescue
|
||||||
|
nil
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -12,5 +12,9 @@ module TagRepr
|
|||||||
parents: tag.parents.map { _1.as_json(BASE) })
|
parents: tag.parents.map { _1.as_json(BASE) })
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def inline tag
|
||||||
|
tag.as_json(BASE).merge(aliases: [], parents: [])
|
||||||
|
end
|
||||||
|
|
||||||
def many(tags) = tags.map { |t| base(t) }
|
def many(tags) = tags.map { |t| base(t) }
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
require 'rails_helper'
|
||||||
|
|
||||||
|
RSpec.describe 'error responses', type: :request do
|
||||||
|
describe 'manual input errors' do
|
||||||
|
it 'returns a stable errors array for bad requests' do
|
||||||
|
user = create(:user)
|
||||||
|
sign_in_as(user)
|
||||||
|
|
||||||
|
put "/users/#{ user.id }", params: { name: ' ' }
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:bad_request)
|
||||||
|
expect(json.fetch('errors')).to contain_exactly(
|
||||||
|
include('code' => 'bad_request',
|
||||||
|
'field' => 'name',
|
||||||
|
'message' => be_present))
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'returns a stable errors array for unprocessable requests' do
|
||||||
|
member = create(:user, :member)
|
||||||
|
tag = create(:tag, :general, name: 'error_response_tag')
|
||||||
|
sign_in_as(member)
|
||||||
|
|
||||||
|
patch "/tags/#{ tag.id }", params: { category: 'nico' }
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:unprocessable_entity)
|
||||||
|
expect(json.fetch('errors')).to contain_exactly(
|
||||||
|
include('code' => 'invalid',
|
||||||
|
'field' => 'category',
|
||||||
|
'message' => be_present))
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
describe 'model validation errors' do
|
||||||
|
it 'returns field, code, and message for model errors' do
|
||||||
|
user = create(:user)
|
||||||
|
sign_in_as(user)
|
||||||
|
|
||||||
|
put "/users/#{ user.id }", params: { name: 'a' * 256 }
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:unprocessable_entity)
|
||||||
|
expect(json.fetch('errors')).to include(
|
||||||
|
include('code' => 'too_long',
|
||||||
|
'field' => 'name',
|
||||||
|
'message' => be_present))
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -57,6 +57,23 @@ RSpec.describe 'Posts API', type: :request do
|
|||||||
post_write_params({ base_version_no: base_version.version_no }.merge(params))
|
post_write_params({ base_version_no: base_version.version_no }.merge(params))
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def count_sql_queries
|
||||||
|
count = 0
|
||||||
|
|
||||||
|
callback = lambda do |_name, _started, _finished, _id, payload|
|
||||||
|
next if payload[:cached]
|
||||||
|
next if ['SCHEMA', 'TRANSACTION'].include?(payload[:name])
|
||||||
|
|
||||||
|
count += 1
|
||||||
|
end
|
||||||
|
|
||||||
|
ActiveSupport::Notifications.subscribed(callback, 'sql.active_record') do
|
||||||
|
yield
|
||||||
|
end
|
||||||
|
|
||||||
|
count
|
||||||
|
end
|
||||||
|
|
||||||
let!(:tag_name) { TagName.create!(name: 'spec_tag') }
|
let!(:tag_name) { TagName.create!(name: 'spec_tag') }
|
||||||
let!(:tag) { Tag.create!(tag_name: tag_name, category: :general) }
|
let!(:tag) { Tag.create!(tag_name: tag_name, category: :general) }
|
||||||
|
|
||||||
@@ -558,6 +575,59 @@ RSpec.describe 'Posts API', type: :request do
|
|||||||
expect(sibling_ids).to include(sibling_post.id)
|
expect(sibling_ids).to include(sibling_post.id)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
it 'does not issue a query per tag or related post' do
|
||||||
|
user = create_member_user!
|
||||||
|
|
||||||
|
tags =
|
||||||
|
15.times.map do |i|
|
||||||
|
tag_name = TagName.create!(name: "show_query_tag_#{ i }")
|
||||||
|
tag = Tag.create!(tag_name:, category: :general)
|
||||||
|
TagName.create!(name: "show_query_alias_#{ i }", canonical: tag_name)
|
||||||
|
PostTag.create!(post: post_record, tag:)
|
||||||
|
tag
|
||||||
|
end
|
||||||
|
|
||||||
|
tags.each_cons(2) do |parent_tag, child_tag|
|
||||||
|
TagImplication.create!(parent_tag:, tag: child_tag)
|
||||||
|
end
|
||||||
|
|
||||||
|
parent_post = Post.create!(
|
||||||
|
title: 'query parent post',
|
||||||
|
url: 'https://example.com/query-parent-post'
|
||||||
|
)
|
||||||
|
sibling_post = Post.create!(
|
||||||
|
title: 'query sibling post',
|
||||||
|
url: 'https://example.com/query-sibling-post'
|
||||||
|
)
|
||||||
|
child_post = Post.create!(
|
||||||
|
title: 'query child post',
|
||||||
|
url: 'https://example.com/query-child-post'
|
||||||
|
)
|
||||||
|
|
||||||
|
PostImplication.create!(post: post_record, parent_post:)
|
||||||
|
PostImplication.create!(post: sibling_post, parent_post:)
|
||||||
|
PostImplication.create!(post: child_post, parent_post: post_record)
|
||||||
|
|
||||||
|
20.times do |i|
|
||||||
|
related_post = Post.create!(
|
||||||
|
title: "query related post #{ i }",
|
||||||
|
url: "https://example.com/query-related-post-#{ i }"
|
||||||
|
)
|
||||||
|
PostSimilarity.create!(post: post_record,
|
||||||
|
target_post: related_post,
|
||||||
|
cos: 1.0 - (i / 100.0))
|
||||||
|
end
|
||||||
|
|
||||||
|
query_count =
|
||||||
|
count_sql_queries do
|
||||||
|
get "/posts/#{ post_record.id }",
|
||||||
|
headers: { 'X-Transfer-Code' => user.inheritance_code }
|
||||||
|
end
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
expect(query_count).to be <= 45
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
context 'when post does not exist' do
|
context 'when post does not exist' do
|
||||||
|
|||||||
@@ -2,17 +2,24 @@ import { useEffect, useState } from 'react'
|
|||||||
|
|
||||||
import PostFormTagsArea from '@/components/PostFormTagsArea'
|
import PostFormTagsArea from '@/components/PostFormTagsArea'
|
||||||
import PostOriginalCreatedTimeField from '@/components/PostOriginalCreatedTimeField'
|
import PostOriginalCreatedTimeField from '@/components/PostOriginalCreatedTimeField'
|
||||||
|
import FieldError from '@/components/common/FieldError'
|
||||||
import Label from '@/components/common/Label'
|
import Label from '@/components/common/Label'
|
||||||
import { useDialogue } from '@/components/dialogues/DialogueProvider'
|
import { useDialogue } from '@/components/dialogues/DialogueProvider'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import { toast } from '@/components/ui/use-toast'
|
import { toast } from '@/components/ui/use-toast'
|
||||||
import { isApiError } from '@/lib/api'
|
import { isApiError } from '@/lib/api'
|
||||||
|
import { extractValidationError } from '@/lib/apiErrors'
|
||||||
import { updatePost } from '@/lib/posts'
|
import { updatePost } from '@/lib/posts'
|
||||||
|
import { inputClass } from '@/lib/utils'
|
||||||
|
|
||||||
import type { FC, FormEvent } from 'react'
|
import type { FC, FormEvent } from 'react'
|
||||||
|
|
||||||
|
import type { FieldErrors } from '@/lib/apiErrors'
|
||||||
import type { Post, Tag } from '@/types'
|
import type { Post, Tag } from '@/types'
|
||||||
|
|
||||||
|
type PostFormField =
|
||||||
|
'parentPostId' | 'tags' | 'originalCreatedFrom' | 'originalCreatedBefore'
|
||||||
|
|
||||||
|
|
||||||
const tagsToStr = (tags: Tag[]): string => {
|
const tagsToStr = (tags: Tag[]): string => {
|
||||||
const result: Tag[] = []
|
const result: Tag[] = []
|
||||||
@@ -34,7 +41,9 @@ type Props = { post: Post
|
|||||||
|
|
||||||
|
|
||||||
const PostEditForm: FC<Props> = ({ post, onSave }) => {
|
const PostEditForm: FC<Props> = ({ post, onSave }) => {
|
||||||
|
const [baseErrors, setBaseErrors] = useState<string[]> ([])
|
||||||
const [disabled, setDisabled] = useState (false)
|
const [disabled, setDisabled] = useState (false)
|
||||||
|
const [fieldErrors, setFieldErrors] = useState<FieldErrors> ({ })
|
||||||
const [originalCreatedBefore, setOriginalCreatedBefore] =
|
const [originalCreatedBefore, setOriginalCreatedBefore] =
|
||||||
useState<string | null> (post.originalCreatedBefore)
|
useState<string | null> (post.originalCreatedBefore)
|
||||||
const [originalCreatedFrom, setOriginalCreatedFrom] =
|
const [originalCreatedFrom, setOriginalCreatedFrom] =
|
||||||
@@ -47,6 +56,9 @@ const PostEditForm: FC<Props> = ({ post, onSave }) => {
|
|||||||
const dialogue = useDialogue ()
|
const dialogue = useDialogue ()
|
||||||
|
|
||||||
const update = async (...args: Parameters<typeof updatePost>) => {
|
const update = async (...args: Parameters<typeof updatePost>) => {
|
||||||
|
setFieldErrors ({ })
|
||||||
|
setBaseErrors ([])
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
const data = await updatePost (...args)
|
const data = await updatePost (...args)
|
||||||
@@ -67,7 +79,18 @@ const PostEditForm: FC<Props> = ({ post, onSave }) => {
|
|||||||
|
|
||||||
if (response?.status !== 409)
|
if (response?.status !== 409)
|
||||||
{
|
{
|
||||||
toast ({ description: '更新はできなかったよ……' })
|
const validationError = extractValidationError<PostFormField> (e)
|
||||||
|
|
||||||
|
if (validationError)
|
||||||
|
{
|
||||||
|
setFieldErrors (validationError.fieldErrors)
|
||||||
|
setBaseErrors (validationError.baseErrors)
|
||||||
|
toast ({ description: '更新はできなかったよ……' })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
toast ({ title: '失敗……', description: '入力を確認してください.' })
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -122,33 +145,41 @@ const PostEditForm: FC<Props> = ({ post, onSave }) => {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<form onSubmit={handleSubmit} className="max-w-xl pt-2 space-y-4">
|
<form onSubmit={handleSubmit} className="max-w-xl pt-2 space-y-4">
|
||||||
|
<FieldError messages={baseErrors}/>
|
||||||
|
|
||||||
{/* タイトル */}
|
{/* タイトル */}
|
||||||
<div>
|
<div>
|
||||||
<Label>タイトル</Label>
|
<Label>タイトル</Label>
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
disabled={disabled}
|
disabled={disabled}
|
||||||
className="w-full border rounded p-2"
|
className={inputClass ()}
|
||||||
value={title ?? ''}
|
value={title ?? ''}
|
||||||
onChange={ev => setTitle (ev.target.value)}/>
|
onChange={ev => setTitle (ev.target.value)}/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* 親投稿 */}
|
{/* 親投稿 */}
|
||||||
<div>
|
<div>
|
||||||
<Label>親投稿</Label>
|
<Label invalid={fieldErrors.parentPostIds && fieldErrors.parentPostIds.length > 0}>
|
||||||
|
親投稿
|
||||||
|
</Label>
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
disabled={disabled}
|
disabled={disabled}
|
||||||
value={parentPostIds}
|
value={parentPostIds}
|
||||||
onChange={e => setParentPostIds (e.target.value)}
|
onChange={e => setParentPostIds (e.target.value)}
|
||||||
className="w-full border p-2 rounded"/>
|
aria-invalid={fieldErrors.parentPostIds && fieldErrors.parentPostIds.length > 0}
|
||||||
|
className={inputClass (fieldErrors.parentPostIds
|
||||||
|
&& fieldErrors.parentPostIds.length > 0)}/>
|
||||||
|
<FieldError messages={fieldErrors.parentPostIds}/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* タグ */}
|
{/* タグ */}
|
||||||
<PostFormTagsArea
|
<PostFormTagsArea
|
||||||
disabled={disabled}
|
disabled={disabled}
|
||||||
tags={tags}
|
tags={tags}
|
||||||
setTags={setTags}/>
|
setTags={setTags}
|
||||||
|
errors={fieldErrors.tags}/>
|
||||||
|
|
||||||
{/* オリジナルの作成日時 */}
|
{/* オリジナルの作成日時 */}
|
||||||
<PostOriginalCreatedTimeField
|
<PostOriginalCreatedTimeField
|
||||||
@@ -156,15 +187,14 @@ const PostEditForm: FC<Props> = ({ post, onSave }) => {
|
|||||||
originalCreatedFrom={originalCreatedFrom}
|
originalCreatedFrom={originalCreatedFrom}
|
||||||
setOriginalCreatedFrom={setOriginalCreatedFrom}
|
setOriginalCreatedFrom={setOriginalCreatedFrom}
|
||||||
originalCreatedBefore={originalCreatedBefore}
|
originalCreatedBefore={originalCreatedBefore}
|
||||||
setOriginalCreatedBefore={setOriginalCreatedBefore}/>
|
setOriginalCreatedBefore={setOriginalCreatedBefore}
|
||||||
|
errors={fieldErrors.originalCreatedAt}/>
|
||||||
|
|
||||||
{/* 送信 */}
|
{/* 送信 */}
|
||||||
<Button
|
<Button type="submit" disabled={disabled}>
|
||||||
type="submit"
|
|
||||||
disabled={disabled}>
|
|
||||||
更新
|
更新
|
||||||
</Button>
|
</Button>
|
||||||
</form>)
|
</form>)
|
||||||
}
|
}
|
||||||
|
|
||||||
export default PostEditForm
|
export default PostEditForm
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
import { useRef, useState } from 'react'
|
import { useRef, useState } from 'react'
|
||||||
|
|
||||||
import TagSearchBox from '@/components/TagSearchBox'
|
import TagSearchBox from '@/components/TagSearchBox'
|
||||||
|
import FieldError from '@/components/common/FieldError'
|
||||||
import Label from '@/components/common/Label'
|
import Label from '@/components/common/Label'
|
||||||
import TextArea from '@/components/common/TextArea'
|
import TextArea from '@/components/common/TextArea'
|
||||||
import { apiGet } from '@/lib/api'
|
import { apiGet } from '@/lib/api'
|
||||||
@@ -33,10 +34,11 @@ const replaceToken = (value: string, start: number, end: number, text: string) =
|
|||||||
|
|
||||||
type Props = Omit<ComponentPropsWithoutRef<'textarea'>, 'value' | 'onChange' | 'onBlur'> & {
|
type Props = Omit<ComponentPropsWithoutRef<'textarea'>, 'value' | 'onChange' | 'onBlur'> & {
|
||||||
tags: string
|
tags: string
|
||||||
setTags: (tags: string) => void }
|
setTags: (tags: string) => void
|
||||||
|
errors?: string[] }
|
||||||
|
|
||||||
|
|
||||||
const PostFormTagsArea: FC<Props> = ({ tags, setTags, ...rest }) => {
|
const PostFormTagsArea: FC<Props> = ({ tags, setTags, errors, ...rest }) => {
|
||||||
const ref = useRef<HTMLTextAreaElement> (null)
|
const ref = useRef<HTMLTextAreaElement> (null)
|
||||||
|
|
||||||
const [bounds, setBounds] = useState<{ start: number; end: number }> ({ start: 0, end: 0 })
|
const [bounds, setBounds] = useState<{ start: number; end: number }> ({ start: 0, end: 0 })
|
||||||
@@ -74,11 +76,12 @@ const PostFormTagsArea: FC<Props> = ({ tags, setTags, ...rest }) => {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="relative w-full">
|
<div className="relative w-full">
|
||||||
<Label>タグ</Label>
|
<Label invalid={errors && errors.length > 0}>タグ</Label>
|
||||||
<TextArea
|
<TextArea
|
||||||
{...rest}
|
{...rest}
|
||||||
ref={ref}
|
ref={ref}
|
||||||
value={tags}
|
value={tags}
|
||||||
|
invalid={errors && errors.length > 0}
|
||||||
onChange={ev => setTags (ev.target.value)}
|
onChange={ev => setTags (ev.target.value)}
|
||||||
onSelect={async (ev: SyntheticEvent<HTMLTextAreaElement>) => {
|
onSelect={async (ev: SyntheticEvent<HTMLTextAreaElement>) => {
|
||||||
const pos = (ev.target as HTMLTextAreaElement).selectionStart
|
const pos = (ev.target as HTMLTextAreaElement).selectionStart
|
||||||
@@ -96,7 +99,8 @@ const PostFormTagsArea: FC<Props> = ({ tags, setTags, ...rest }) => {
|
|||||||
: [] as Tag[]}
|
: [] as Tag[]}
|
||||||
activeIndex={-1}
|
activeIndex={-1}
|
||||||
onSelect={handleTagSelect}/>)}
|
onSelect={handleTagSelect}/>)}
|
||||||
|
<FieldError messages={errors}/>
|
||||||
</div>)
|
</div>)
|
||||||
}
|
}
|
||||||
|
|
||||||
export default PostFormTagsArea
|
export default PostFormTagsArea
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import DateTimeField from '@/components/common/DateTimeField'
|
import DateTimeField from '@/components/common/DateTimeField'
|
||||||
|
import { FieldError } from '@/components/common/FieldError'
|
||||||
import Label from '@/components/common/Label'
|
import Label from '@/components/common/Label'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
|
|
||||||
@@ -9,21 +10,28 @@ type Props = {
|
|||||||
originalCreatedFrom: string | null
|
originalCreatedFrom: string | null
|
||||||
setOriginalCreatedFrom: (x: string | null) => void
|
setOriginalCreatedFrom: (x: string | null) => void
|
||||||
originalCreatedBefore: string | null
|
originalCreatedBefore: string | null
|
||||||
setOriginalCreatedBefore: (x: string | null) => void }
|
setOriginalCreatedBefore: (x: string | null) => void
|
||||||
|
errors?: string[] }
|
||||||
|
|
||||||
|
|
||||||
const PostOriginalCreatedTimeField: FC<Props> = ({ disabled,
|
const PostOriginalCreatedTimeField: FC<Props> = (
|
||||||
originalCreatedFrom,
|
{ disabled,
|
||||||
setOriginalCreatedFrom,
|
originalCreatedFrom,
|
||||||
originalCreatedBefore,
|
setOriginalCreatedFrom,
|
||||||
setOriginalCreatedBefore }) => (
|
originalCreatedBefore,
|
||||||
|
setOriginalCreatedBefore,
|
||||||
|
errors }: Props,
|
||||||
|
) => (
|
||||||
<div>
|
<div>
|
||||||
<Label>オリジナルの作成日時</Label>
|
<Label invalid={errors && errors.length > 0}>オリジナルの作成日時</Label>
|
||||||
|
|
||||||
<div className="my-1 flex">
|
<div className="my-1 flex">
|
||||||
<div className="w-80">
|
<div className="w-80">
|
||||||
<DateTimeField
|
<DateTimeField
|
||||||
className="mr-2"
|
className="mr-2"
|
||||||
disabled={disabled ?? false}
|
disabled={disabled ?? false}
|
||||||
|
aria-invalid={errors && errors.length > 0}
|
||||||
|
invalid={errors && errors.length > 0}
|
||||||
value={originalCreatedFrom ?? undefined}
|
value={originalCreatedFrom ?? undefined}
|
||||||
onChange={setOriginalCreatedFrom}
|
onChange={setOriginalCreatedFrom}
|
||||||
onBlur={ev => {
|
onBlur={ev => {
|
||||||
@@ -51,11 +59,14 @@ const PostOriginalCreatedTimeField: FC<Props> = ({ disabled,
|
|||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="my-1 flex">
|
<div className="my-1 flex">
|
||||||
<div className="w-80">
|
<div className="w-80">
|
||||||
<DateTimeField
|
<DateTimeField
|
||||||
className="mr-2"
|
className="mr-2"
|
||||||
disabled={disabled}
|
disabled={disabled}
|
||||||
|
aria-invalid={errors && errors.length > 0}
|
||||||
|
invalid={errors && errors.length > 0}
|
||||||
value={originalCreatedBefore ?? undefined}
|
value={originalCreatedBefore ?? undefined}
|
||||||
onChange={setOriginalCreatedBefore}/>
|
onChange={setOriginalCreatedBefore}/>
|
||||||
より前
|
より前
|
||||||
@@ -71,6 +82,8 @@ const PostOriginalCreatedTimeField: FC<Props> = ({ disabled,
|
|||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<FieldError messages={errors}/>
|
||||||
</div>)
|
</div>)
|
||||||
|
|
||||||
export default PostOriginalCreatedTimeField
|
export default PostOriginalCreatedTimeField
|
||||||
|
|||||||
@@ -22,10 +22,11 @@ type Props = Omit<ComponentPropsWithoutRef<'input'>, 'onChange'> & {
|
|||||||
value?: string
|
value?: string
|
||||||
onChange?: (isoUTC: string | null) => void
|
onChange?: (isoUTC: string | null) => void
|
||||||
className?: string
|
className?: string
|
||||||
onBlur?: (ev: FocusEvent<HTMLInputElement>) => void }
|
onBlur?: (ev: FocusEvent<HTMLInputElement>) => void
|
||||||
|
invalid?: boolean }
|
||||||
|
|
||||||
|
|
||||||
const DateTimeField: FC<Props> = ({ value, onChange, className, onBlur, ...rest }) => {
|
const DateTimeField: FC<Props> = ({ value, onChange, className, onBlur, invalid, ...rest }) => {
|
||||||
const [local, setLocal] = useState ('')
|
const [local, setLocal] = useState ('')
|
||||||
|
|
||||||
useEffect (() => {
|
useEffect (() => {
|
||||||
@@ -35,9 +36,19 @@ const DateTimeField: FC<Props> = ({ value, onChange, className, onBlur, ...rest
|
|||||||
return (
|
return (
|
||||||
<input
|
<input
|
||||||
{...rest}
|
{...rest}
|
||||||
className={cn ('border rounded p-2', className)}
|
className={cn ('border rounded p-2',
|
||||||
|
(invalid
|
||||||
|
? ['border-red-500 bg-red-50 text-red-900',
|
||||||
|
'focus:border-red-500 focus:outline-none',
|
||||||
|
'focus:ring-2 focus:ring-red-200',
|
||||||
|
'dark:border-red-500 dark:bg-red-950/30 dark:text-red-100']
|
||||||
|
: ['border-gray-300',
|
||||||
|
'focus:border-blue-500 focus:outline-none',
|
||||||
|
'focus:ring-2 focus:ring-blue-200']),
|
||||||
|
className)}
|
||||||
type="datetime-local"
|
type="datetime-local"
|
||||||
value={local}
|
value={local}
|
||||||
|
aria-invalid={invalid}
|
||||||
onChange={ev => {
|
onChange={ev => {
|
||||||
const v = ev.target.value
|
const v = ev.target.value
|
||||||
setLocal (v)
|
setLocal (v)
|
||||||
@@ -46,4 +57,4 @@ const DateTimeField: FC<Props> = ({ value, onChange, className, onBlur, ...rest
|
|||||||
onBlur={onBlur}/>)
|
onBlur={onBlur}/>)
|
||||||
}
|
}
|
||||||
|
|
||||||
export default DateTimeField
|
export default DateTimeField
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import type { FC } from 'react'
|
||||||
|
|
||||||
|
type Props = { messages?: string[] }
|
||||||
|
|
||||||
|
|
||||||
|
export const FieldError: FC<Props> = ({ messages }: Props) => {
|
||||||
|
if (!(messages) || messages.length === 0)
|
||||||
|
return null
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ul className="mt-1 space-y-1 text-red-700 dark:text-red-300">
|
||||||
|
{messages.map ((message, i) => <li key={i}>{message}</li>)}
|
||||||
|
</ul>)
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
export default FieldError
|
||||||
@@ -1,32 +1,39 @@
|
|||||||
import React from 'react'
|
import React from 'react'
|
||||||
|
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
import type { FC } from 'react'
|
import type { FC } from 'react'
|
||||||
|
|
||||||
type Props = { children: React.ReactNode
|
type Props = { children: React.ReactNode
|
||||||
checkBox?: { label: string
|
checkBox?: { label: string
|
||||||
checked: boolean
|
checked: boolean
|
||||||
onChange: (event: React.ChangeEvent<HTMLInputElement>) => void } }
|
onChange: (event: React.ChangeEvent<HTMLInputElement>) => void }
|
||||||
|
invalid?: boolean }
|
||||||
|
|
||||||
|
|
||||||
const Label: FC<Props> = ({ children, checkBox }) => {
|
const Label: FC<Props> = ({ children, checkBox, invalid }: Props) => {
|
||||||
|
const labelClassName = cn ('block font-semibold mb-1',
|
||||||
|
invalid && 'text-red-700 dark:text-red-300')
|
||||||
|
|
||||||
if (!(checkBox))
|
if (!(checkBox))
|
||||||
{
|
{
|
||||||
return (
|
return (
|
||||||
<label className="block font-semibold mb-1">
|
<label className={labelClassName}>
|
||||||
{children}
|
{children}
|
||||||
</label>)
|
</label>)
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex gap-2 mb-1">
|
<div className="flex gap-2 mb-1">
|
||||||
<label className="flex-1 block font-semibold">{children}</label>
|
<label className="flex-1 block font-semibold">{children}</label>
|
||||||
<label className="flex items-center block gap-1">
|
<label className="flex items-center block gap-1">
|
||||||
<input type="checkbox"
|
<input type="checkbox"
|
||||||
checked={checkBox.checked}
|
checked={checkBox.checked}
|
||||||
onChange={checkBox.onChange}/>
|
onChange={checkBox.onChange}/>
|
||||||
{checkBox.label}
|
{checkBox.label}
|
||||||
</label>
|
</label>
|
||||||
</div>)
|
</div>)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
export default Label
|
export default Label
|
||||||
|
|||||||
@@ -1,9 +1,25 @@
|
|||||||
import { forwardRef } from 'react'
|
import { forwardRef } from 'react'
|
||||||
|
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
import type { TextareaHTMLAttributes } from 'react'
|
import type { TextareaHTMLAttributes } from 'react'
|
||||||
|
|
||||||
type Props = TextareaHTMLAttributes<HTMLTextAreaElement>
|
type Props = TextareaHTMLAttributes<HTMLTextAreaElement> & { invalid?: boolean }
|
||||||
|
|
||||||
|
|
||||||
export default forwardRef<HTMLTextAreaElement, Props> (({ ...props }, ref) => (
|
export default forwardRef<HTMLTextAreaElement, Props> (
|
||||||
<textarea ref={ref} className="rounded border w-full p-2 h-32" {...props}/>))
|
({ className, invalid = false, ...props }, ref) => (
|
||||||
|
<textarea
|
||||||
|
ref={ref}
|
||||||
|
aria-invalid={invalid}
|
||||||
|
className={cn ('rounded border w-full p-2 h-32',
|
||||||
|
(invalid
|
||||||
|
? ['border-red-500 bg-red-50 text-red-900',
|
||||||
|
'focus:border-red-500 focus:outline-none focus:ring-2',
|
||||||
|
'foucs:ring-red-200',
|
||||||
|
'dark:border-red-500 dark:bg-red-950/30 dark:text-red-100']
|
||||||
|
: ['border-gray-300',
|
||||||
|
'focus:border-blue-500 focus:outline-none focus:ring-2',
|
||||||
|
'focus:ring-blue-200']),
|
||||||
|
className)}
|
||||||
|
{...props}/>))
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
import toCamel from 'camelcase-keys'
|
||||||
|
|
||||||
|
import { isApiError } from '@/lib/api'
|
||||||
|
|
||||||
|
export type FieldErrors<T extends string = string> = Partial<Record<T, string[]>>
|
||||||
|
|
||||||
|
export type ValidationError<T extends string = string> =
|
||||||
|
{ message: string
|
||||||
|
fieldErrors: FieldErrors<T>
|
||||||
|
baseErrors: string[] }
|
||||||
|
|
||||||
|
type RawValidationError = { type?: string
|
||||||
|
message?: string
|
||||||
|
errors?: Record<string, string[]>
|
||||||
|
baseErrors?: string[] }
|
||||||
|
|
||||||
|
|
||||||
|
export const extractValidationError = <T extends string = string> (err: unknown) => {
|
||||||
|
if (!(isApiError (err)) || err.response?.status !== 422)
|
||||||
|
return null
|
||||||
|
|
||||||
|
const data = toCamel ((err.response.data ?? { }) as Record<string, unknown>,
|
||||||
|
{ deep: true }) as RawValidationError
|
||||||
|
|
||||||
|
if (data.type !== 'validation_error' && !(data.errors))
|
||||||
|
return null
|
||||||
|
|
||||||
|
return { message: data.message ?? '入力内容を確認してください.',
|
||||||
|
fieldErrors: (data.errors ?? { }) as FieldErrors<T>,
|
||||||
|
baseErrors: data.baseErrors ?? [] }
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
|
||||||
|
import { canEditContent } from '@/lib/users'
|
||||||
|
|
||||||
|
import type { UserRole } from '@/types'
|
||||||
|
|
||||||
|
const userWithRole = (role: UserRole) => ({ role })
|
||||||
|
|
||||||
|
describe ('user permission helpers', () => {
|
||||||
|
it ('allows admins and members to edit content', () => {
|
||||||
|
expect (canEditContent (userWithRole ('admin'))).toBe (true)
|
||||||
|
expect (canEditContent (userWithRole ('member'))).toBe (true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it ('does not allow guests or missing users to edit content', () => {
|
||||||
|
expect (canEditContent (userWithRole ('guest'))).toBe (false)
|
||||||
|
expect (canEditContent (null)).toBe (false)
|
||||||
|
expect (canEditContent (undefined)).toBe (false)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
import type { User, UserRole } from '@/types'
|
||||||
|
|
||||||
|
const CONTENT_EDITOR_ROLES: readonly UserRole[] = ['admin', 'member']
|
||||||
|
|
||||||
|
export const canEditContent = (
|
||||||
|
user: Pick<User, 'role'> | null | undefined,
|
||||||
|
): boolean => user != null && CONTENT_EDITOR_ROLES.includes (user.role)
|
||||||
@@ -71,3 +71,15 @@ export const originalCreatedAtString = (
|
|||||||
.join (' '))
|
.join (' '))
|
||||||
return rtn === '〜' ? '年月日不詳' : rtn
|
return rtn === '〜' ? '年月日不詳' : rtn
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
export const inputClass = (invalid?: boolean, className?: string): string =>
|
||||||
|
cn ('w-full rounded border p-2',
|
||||||
|
(invalid
|
||||||
|
? ['border-red-500 bg-red-50 text-red-900',
|
||||||
|
'placeholder:text-red-300',
|
||||||
|
'focus:border-red-500 focus:outline-none focus:ring-2 focus:ring-red-200',
|
||||||
|
'dark:border-red-500 dark:bg-red-950/30 dark:text-red-100']
|
||||||
|
: ['border-gray-300',
|
||||||
|
'focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-200']),
|
||||||
|
className)
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ import { motion } from 'framer-motion'
|
|||||||
import { useEffect, useRef, useState } from 'react'
|
import { useEffect, useRef, useState } from 'react'
|
||||||
import { Helmet } from 'react-helmet-async'
|
import { Helmet } from 'react-helmet-async'
|
||||||
import { useParams } from 'react-router-dom'
|
import { useParams } from 'react-router-dom'
|
||||||
|
|
||||||
import PostEditForm from '@/components/PostEditForm'
|
import PostEditForm from '@/components/PostEditForm'
|
||||||
import PostEmbed from '@/components/PostEmbed'
|
import PostEmbed from '@/components/PostEmbed'
|
||||||
import PostList from '@/components/PostList'
|
import PostList from '@/components/PostList'
|
||||||
@@ -16,6 +15,7 @@ import { SITE_TITLE } from '@/config'
|
|||||||
import { isApiError } from '@/lib/api'
|
import { isApiError } from '@/lib/api'
|
||||||
import { fetchPost, toggleViewedFlg } from '@/lib/posts'
|
import { fetchPost, toggleViewedFlg } from '@/lib/posts'
|
||||||
import { postsKeys, tagsKeys } from '@/lib/queryKeys'
|
import { postsKeys, tagsKeys } from '@/lib/queryKeys'
|
||||||
|
import { canEditContent } from '@/lib/users'
|
||||||
import { cn } from '@/lib/utils'
|
import { cn } from '@/lib/utils'
|
||||||
import NotFound from '@/pages/NotFound'
|
import NotFound from '@/pages/NotFound'
|
||||||
import ServiceUnavailable from '@/pages/ServiceUnavailable'
|
import ServiceUnavailable from '@/pages/ServiceUnavailable'
|
||||||
@@ -28,6 +28,7 @@ type Props = { user: User | null }
|
|||||||
|
|
||||||
|
|
||||||
const PostDetailPage: FC<Props> = ({ user }) => {
|
const PostDetailPage: FC<Props> = ({ user }) => {
|
||||||
|
const editable = canEditContent (user)
|
||||||
const { id } = useParams ()
|
const { id } = useParams ()
|
||||||
const postId = String (id ?? '')
|
const postId = String (id ?? '')
|
||||||
const postKey = postsKeys.show (postId)
|
const postKey = postsKeys.show (postId)
|
||||||
@@ -164,7 +165,7 @@ const PostDetailPage: FC<Props> = ({ user }) => {
|
|||||||
? <PostList posts={post.related}/>
|
? <PostList posts={post.related}/>
|
||||||
: 'まだないよ(笑)'}
|
: 'まだないよ(笑)'}
|
||||||
</Tab>
|
</Tab>
|
||||||
{['admin', 'member'].some (r => user?.role === r) && (
|
{editable && (
|
||||||
<Tab name="編輯">
|
<Tab name="編輯">
|
||||||
<PostEditForm
|
<PostEditForm
|
||||||
post={post}
|
post={post}
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import { Button } from '@/components/ui/button'
|
|||||||
import { toast } from '@/components/ui/use-toast'
|
import { toast } from '@/components/ui/use-toast'
|
||||||
import { SITE_TITLE } from '@/config'
|
import { SITE_TITLE } from '@/config'
|
||||||
import { apiGet, apiPost } from '@/lib/api'
|
import { apiGet, apiPost } from '@/lib/api'
|
||||||
|
import { canEditContent } from '@/lib/users'
|
||||||
import Forbidden from '@/pages/Forbidden'
|
import Forbidden from '@/pages/Forbidden'
|
||||||
|
|
||||||
import type { FC } from 'react'
|
import type { FC } from 'react'
|
||||||
@@ -22,7 +23,7 @@ type Props = { user: User | null }
|
|||||||
|
|
||||||
|
|
||||||
const PostNewPage: FC<Props> = ({ user }) => {
|
const PostNewPage: FC<Props> = ({ user }) => {
|
||||||
const editable = ['admin', 'member'].some (r => user?.role === r)
|
const editable = canEditContent (user)
|
||||||
|
|
||||||
const navigate = useNavigate ()
|
const navigate = useNavigate ()
|
||||||
|
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import MainArea from '@/components/layout/MainArea'
|
|||||||
import { toast } from '@/components/ui/use-toast'
|
import { toast } from '@/components/ui/use-toast'
|
||||||
import { SITE_TITLE } from '@/config'
|
import { SITE_TITLE } from '@/config'
|
||||||
import { apiGet, apiPut } from '@/lib/api'
|
import { apiGet, apiPut } from '@/lib/api'
|
||||||
|
import { canEditContent } from '@/lib/users'
|
||||||
|
|
||||||
import type { NicoTag, Tag, User } from '@/types'
|
import type { NicoTag, Tag, User } from '@/types'
|
||||||
|
|
||||||
@@ -25,7 +26,7 @@ const NicoTagListPage: FC<Props> = ({ user }) => {
|
|||||||
|
|
||||||
const loaderRef = useRef<HTMLDivElement | null> (null)
|
const loaderRef = useRef<HTMLDivElement | null> (null)
|
||||||
|
|
||||||
const memberFlg = ['admin', 'member'].some (r => user?.role === r)
|
const editable = canEditContent (user)
|
||||||
|
|
||||||
const applyLoadedTags = useCallback ((data: { tags: NicoTag[]; nextCursor: string },
|
const applyLoadedTags = useCallback ((data: { tags: NicoTag[]; nextCursor: string },
|
||||||
withCursor: boolean) => {
|
withCursor: boolean) => {
|
||||||
@@ -117,7 +118,7 @@ const NicoTagListPage: FC<Props> = ({ user }) => {
|
|||||||
<tr>
|
<tr>
|
||||||
<th className="p-2 text-left">ニコニコタグ</th>
|
<th className="p-2 text-left">ニコニコタグ</th>
|
||||||
<th className="p-2 text-left">連携タグ</th>
|
<th className="p-2 text-left">連携タグ</th>
|
||||||
{memberFlg && <th></th>}
|
{editable && <th></th>}
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
@@ -139,7 +140,7 @@ const NicoTagListPage: FC<Props> = ({ user }) => {
|
|||||||
withCount={false}/>
|
withCount={false}/>
|
||||||
</span>))}
|
</span>))}
|
||||||
</td>
|
</td>
|
||||||
{memberFlg && (
|
{editable && (
|
||||||
<td className="p-2">
|
<td className="p-2">
|
||||||
<a href="#" onClick={ev => {
|
<a href="#" onClick={ev => {
|
||||||
ev.preventDefault ()
|
ev.preventDefault ()
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import { toast } from '@/components/ui/use-toast'
|
|||||||
import { SITE_TITLE } from '@/config'
|
import { SITE_TITLE } from '@/config'
|
||||||
import { apiGet, apiPut } from '@/lib/api'
|
import { apiGet, apiPut } from '@/lib/api'
|
||||||
import { wikiKeys } from '@/lib/queryKeys'
|
import { wikiKeys } from '@/lib/queryKeys'
|
||||||
|
import { canEditContent } from '@/lib/users'
|
||||||
import Forbidden from '@/pages/Forbidden'
|
import Forbidden from '@/pages/Forbidden'
|
||||||
|
|
||||||
import 'react-markdown-editor-lite/lib/index.css'
|
import 'react-markdown-editor-lite/lib/index.css'
|
||||||
@@ -24,7 +25,7 @@ type Props = { user: User | null }
|
|||||||
|
|
||||||
|
|
||||||
const WikiEditPage: FC<Props> = ({ user }) => {
|
const WikiEditPage: FC<Props> = ({ user }) => {
|
||||||
const editable = ['admin', 'member'].some (r => user?.role === r)
|
const editable = canEditContent (user)
|
||||||
|
|
||||||
const { id } = useParams ()
|
const { id } = useParams ()
|
||||||
|
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import MainArea from '@/components/layout/MainArea'
|
|||||||
import { toast } from '@/components/ui/use-toast'
|
import { toast } from '@/components/ui/use-toast'
|
||||||
import { SITE_TITLE } from '@/config'
|
import { SITE_TITLE } from '@/config'
|
||||||
import { apiPost } from '@/lib/api'
|
import { apiPost } from '@/lib/api'
|
||||||
|
import { canEditContent } from '@/lib/users'
|
||||||
import Forbidden from '@/pages/Forbidden'
|
import Forbidden from '@/pages/Forbidden'
|
||||||
|
|
||||||
import 'react-markdown-editor-lite/lib/index.css'
|
import 'react-markdown-editor-lite/lib/index.css'
|
||||||
@@ -22,7 +23,7 @@ type Props = { user: User | null }
|
|||||||
|
|
||||||
|
|
||||||
const WikiNewPage: FC<Props> = ({ user }) => {
|
const WikiNewPage: FC<Props> = ({ user }) => {
|
||||||
const editable = ['admin', 'member'].some (r => user?.role === r)
|
const editable = canEditContent (user)
|
||||||
|
|
||||||
const location = useLocation ()
|
const location = useLocation ()
|
||||||
const navigate = useNavigate ()
|
const navigate = useNavigate ()
|
||||||
|
|||||||
新しい課題から参照
ユーザをブロックする