importtype{ NextApiRequest, NextApiResponse }from"next";import axios,{ AxiosResponse }from"axios";import qs from"qs";import resultInfo from"../../entity/result.json";typeResultInfo=typeof resultInfo;exportdefaultasyncfunctionsendtoChatwork(
req: NextApiRequest,
res: NextApiResponse
){//POSTデータ取得 const content:any= req.body.content;//set post fieldsconst params = qs.stringify({
body: content,
self_unread:"1",});//API tokenconst token ='********************************';//ルームIDconst room_id ='*********';//Chatwork URLconst url =`https://api.chatwork.com/v2/rooms/${room_id}/messages`;try{const ret: AxiosResponse<ResultInfo>=await axios.post(
url,
params,{
headers:{
Accept:"application/json","Content-Type":"application/x-www-form-urlencoded",'x-chatworktoken': token,},
withCredentials:true,});//if message is sent successfully,chatwork returns message-idif(ret.data !=null){
res.status(200).json({status:200,message:"Chatworkグループにメセッジを送信しました!"});}else{
res.status(299).json({status:299,message:"Chatworkグループにメセッジ送信が失敗しました!"});}}catch(error){console.log("res.status");if((error as Error).message =="Request failed with status code 400"){
res
.status(400).json({ status:400,message:"リクエストパラメーターが不足している、および不正な値が指定されています!"});}elseif((error as Error).message =="Request failed with status code 401"){
res
.status(401).json({ status:401,message:"API認証失敗しました!"});}elseif((error as Error).message =="Request failed with status code 403"){
res
.status(403).json({ status:403,message:"チャットにメッセージを投稿する権限がありません!"});}elseif((error as Error).message =="Request failed with status code 404"){
res
.status(404).json({ status:404,message:"ページが見つかりません!"});}elseif((error as Error).message =="Request failed with status code 429"){
res
.status(429).json({ status:429,message:"APIの利用回数制限およびチャット単位のメッセージ・タスク投稿回数制限を超過した!"});}else{
res
.status(500).json({ status:500,message:"内部サーバーエラーが発生しました!"});}}}
レスポンスの型の為、result.jsonを追加
/entity/result.json
{"status":0,"message":"string","error":"string"}
フロント側のメッセージ送信機能を編集
pages/chatwork.tsx
/* other imports */import{ FetchError }from"../lib/fetchError"/* other functions */constsendMessageToChatwork=async(content:string)=>{const body ={
content: content,};try{const response: Response =awaitfetch("/api/sendtoChatwork",{
method:"POST",
headers:{"Content-Type":"application/json"},
body:JSON.stringify(body),});const result: ResultInfo =await response.json();setStatusMessage(result.message);}catch(error){if(error instanceofFetchError){setStatusMessage(error.data.message);}else{console.error("An unexpected error happened:", error);}}};
lib/fetchError.ts
exportclassFetchErrorextendsError{
response: Response;
data:{
message:string;};constructor({
message,
response,
data,}:{
message:string;
response: Response;
data:{
message:string;};}){// Pass remaining arguments (including vendor specific ones) to parent constructorsuper(message);// Maintains proper stack trace for where our error was thrown (only available on V8)if(Error.captureStackTrace){
Error.captureStackTrace(this, FetchError);}this.name ="FetchError";this.response = response;this.data = data ??{ message: message };}}