PageSourceSearch

https://www.kintetsu-g-hd.co.jp/common-hd/microcms/modules/hd-news/get-news-list.js

js kintetsu-g-hd.co.jp collected 2026-10-02 04:13:37 UTC 9,588 bytes, 227 lines download raw bytes

1import { microcmsNews } from "../../vars/microcms.js";
2import { getParam } from "../../functions/get-param.js";
3import { formatDate } from "../../functions/format-date.js";
4import { nl2br } from "../../functions/nl2br.js";
5import { checkFileExists } from "../../functions/check-file-exists.js";
6import { createYearsArray } from "../../functions/create-years-array.js";
7import { FILE_TYPE_PDF, FILE_TYPE_LINK, FILE_TYPE_HTML, CATEGORY, HD_CATEGORY_QUERY, HD_SEGMENT } from "../../vars/news-vars.js";
8import { PDF_UPLOAD_PATH } from "../../vars/news-vars.js";
9
10
11/**
12 * ----------------------------------------------
13 * hdお知らせ一覧を取得
14 * --
15 * @param path - 該当のページからpost.htmlまでの間のパス
16 * @param limit - 一覧表示する記事の上限数
17 * @param year - 取得するニュースリリースの公開年
18 * ----------------------------------------------
19 */
20export const getNewsList = (path, limit, endPoint, year = null) => {
21  // ----------------------------------------------
22  // 現在の年とバックナンバーを取得
23  // ----------------------------------------------
24  let fetchUrl = '';
25  if (endPoint == 'kghd-news') {
26    const PreviewDate = null;
27    const Now = PreviewDate != null ? new Date(PreviewDate) : new Date();
28    const CurrentYear = Now.getFullYear().toString();
29    const TargetYear = year !== null ? year : CurrentYear;
30    // ページが表示されるタイミングが「公開開始日」か「公開終了日」と
31    // 同じ場合は記事が取得できないので、1秒時間をずらす
32    const NowStart = PreviewDate != null ? new Date(PreviewDate) : new Date();
33    NowStart.setSeconds(NowStart.getSeconds() + 1)
34    const NowEnd = PreviewDate != null ? new Date(PreviewDate) : new Date();
35    NowEnd.setSeconds(NowEnd.getSeconds() - 1)
36    const Now_Start_ISO  = NowStart.toISOString();
37    const Now_End_ISO  = NowEnd.toISOString();
38
39    // 最も古い記事の公開年を取得
40    fetchUrl = `https://${microcmsNews.SERVICE_ID}.microcms.io/api/v1/${endPoint}?fields=display_date&orders=display_date&limit=1&filters=web_view[equals]false[and]${HD_CATEGORY_QUERY}`; 
41    fetch(fetchUrl, {
42      headers: {
43        "X-MICROCMS-API-KEY": microcmsNews.API_KEY,
44      },
45    })
46    .then((response) => response.json())
47    .then((json) => {
48      const OldestPostYear = json.contents[0].display_date.substr(0,4);
49      const PostYears = createYearsArray(parseInt(OldestPostYear), parseInt(CurrentYear));
50      PostYears.sort(function(a,b){
51        if( a > b ) return -1;
52        if( a < b ) return 1;
53        return 0;
54      });
55
56      let i = 2; //1はニュースリリースTOPに利用
57      for (const year of PostYears) {
58        const BacknumberLink = `/news-hd/index.html?year=${year}`;  
59
60        // PC
61        $('.slicknav').append(`
62          <li class="sub_cat_${i.toString().padStart(2, 0)}"><a href="${BacknumberLink}">${year.toString()}å¹´</a></li>
63        `);  
64        // SP
65        $('.slicknav_nav').append(`
66        <li class="sub_cat_${i.toString().padStart(2, 0)}"><a href="${BacknumberLink}">${year.toString()}å¹´</a></li>
67      `);  
68        i++;
69      }
70    });
71
72    // year指定がない時、クエリに付与しない
73    let year_query ="";
74    if(TargetYear !== null){
75      // UTCとの時差を考慮
76      const From = PreviewDate != null ? new Date(PreviewDate) : new Date();
77      From.setUTCFullYear(parseInt(TargetYear) - 1);
78      From.setUTCMonth(12);
79      From.setUTCDate(0);
80      From.setUTCHours(14);
81      From.setUTCMinutes(59);
82
83      const End = PreviewDate != null ? new Date(PreviewDate) : new Date();
84      End.setUTCFullYear(parseInt(TargetYear));
85      End.setUTCMonth(12);
86      End.setUTCDate(0);
87      End.setUTCHours(14);
88      End.setUTCMinutes(59);
89
90      const CurrentYearFrom = From.toISOString();
91      const CurrentYearEnd = End.toISOString();
92
93      year_query = `[and](display_date[greater_than]${CurrentYearFrom}[and]display_date[less_than]${CurrentYearEnd})`;
94    }
95
96    fetchUrl = `https://${microcmsNews.SERVICE_ID}.microcms.io/api/v1/${endPoint}?orders=-priority,-display_date,-start&limit=${limit}&filters=web_view[equals]false${year_query}[and]((start[less_than]${Now_Start_ISO}[or]start[not_exists])[and](end[greater_than]${Now_End_ISO}[or]end[not_exists]))[and]${HD_CATEGORY_QUERY}`;
97  } else {
98    fetchUrl = `https://${microcmsNews.SERVICE_ID}.microcms.io/api/v1/${endPoint}?orders=-priority,-display_date,-start&limit=${limit}&filters=web_view[equals]false`;
99  }
100
101  $(function () {
102    // ----------------------------------------------
103    // お知らせ一覧を取得
104    // ----------------------------------------------
105    fetch(fetchUrl, {
106      headers: {
107        "X-MICROCMS-API-KEY": microcmsNews.API_KEY,
108      },
109    })
110    .then((response) => response.json())
111    .then((json) => {
112      if (json.contents.length > 0) {
113        // ----------------------------------------------
114        // 投稿があるとき
115        // ----------------------------------------------
116        for (const info of json.contents) {
117          const FileType = info.filetype[0] ?? null;                 // ファイルタイプ
118          const TitleList = info.title_list ?? null;                 // 一覧ページ表示用タイトル
119          const DisplayDate = info.display_date ?? null;             // 表示日
120          const Title = TitleList !== null ? nl2br(TitleList) : nl2br(info.title); // タイトル
121          let seg_class ="";                                         // カテゴリー
122          const category =  info.category ?? null;
123          for (let i = 0; i < CATEGORY[0].length; i++) {
124            if (CATEGORY[0][i].value == category) {
125              seg_class = CATEGORY[0][i]['key'];
126              break;
127            }
128          }
129          // segment を調べる
130          let seg_name ="";
131          HD_SEGMENT.map((segment) => {
132            if(segment.key == seg_class){
133              seg_name = segment.seg_name;
134            }
135          });
136
137
138          let pageLink = '';
139          if (FileType == FILE_TYPE_PDF) {
140            // PDFの場合
141            const Pdf = info.pdf ?? null;
142            const PdfFile = Pdf.url ? Pdf.url.url : null;
142 // PDFファイル(microCMS管理)
143            const PdfRealFile = Pdf.pdf_real_file         // PDFファイル(実態ファイル)
144              ? Pdf.pdf_real_file
145              : null;
146            if (PdfFile !== null) {
147              pageLink = `
148              <a href="${PdfFile}" target="_blank" rel="noopener noreferrer">
149                ${Title}
150              </a>
151              `;
152
153            } else if (PdfRealFile !== null) {
154              const filePath = PDF_UPLOAD_PATH['news-hd'] + PdfRealFile;
155              checkFileExists(filePath)
156              .then((exists) => {
157                if (exists) {
158                  $('#hd-news-dd'+info.id).append(`
159                    <a href="${filePath}" target="_blank" rel="noopener noreferrer">
160                      ${Title}
161                    </a>
162                  `);
163                  $(`#news_hd_${seg_name} > dl > #hd-news-dd${info.id}`).append(`
164                    <a href="${filePath}" target="_blank" rel="noopener noreferrer">
165                      ${Title}
166                    </a>
167                  `);
168                } else {
169                  $('#hd-news-dt'+info.id).remove();
170                  $('#hd-news-dd'+info.id).remove();
171                }
172              });
173            } else {
174              // PDFが無い場合は処理をスキップ
175              continue;
176            }
177          } else if (FileType == FILE_TYPE_LINK) {
178            // 外部リンクの場合
179            const Link = info.link ?? null;
180            const WinFlag = Link.win_flag ? Link.win_flag : false; // 別タブ表示
181            const LinkUrl = Link.link ?? '';                       // 外部リンク先
182
183            pageLink = `
184            <a href="${LinkUrl}" ${WinFlag ? ' target="_blank" rel="noopener noreferrer"' : ''}>
185              ${Title}
186            </a>
187            `;
188          } else if (FileType == FILE_TYPE_HTML) {
189            // HTMLファイルの場合
190            pageLink = `
191            <a href="${path}detail.html?id=${info.id}" target="_blank" rel="noopener noreferrer">
192              ${Title}
193            </a>
194            `;
195          } else {
196            // ファイルタイプの指定が無い場合はスキップ
197            continue;
198          }
199
200
201          let addItem = `
202          <dt class="icon_${seg_class}" id="hd-news-dt${info.id}"><span>${formatDate(DisplayDate, false, ['.', '.', ''])}</span></dt>
203          <dd id="hd-news-dd${info.id}">
204            ${pageLink}
205          </dd>
206          `;
207          
208          $('#news_hd_all > dl').append(addItem); //すべてに追加
209          $(`#news_hd_${seg_name} > dl`).append(addItem); // 各事業区分
210        }
211      } else {
212        // ----------------------------------------------
213        // 投稿がないとき
214        // ----------------------------------------------
215      }
216    })
217    .then(
218        // ----------------------------------------------
219        // すべての処理が終わった時
220        // ----------------------------------------------
221        
222    )
223    .catch((e) => {
224      console.log(e.message);
225    });
226  });
227};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.