NextPageでhoge is missing in props validationが出る

React.FC では発生しないエラーがNextPageを使ったところ発生しました


type Props = {
  nodes: Array<Node>;
};

const Index: NextPage<Props> = (props) => {
  const { nodes } = props;
  // 省略
}
このエラー自体はコンパイル時にエラーとして発生しないですが、eslintの設定上エラーを引き起こせたりエディタで警告出るので開発する上ではやはり避けられません

最初に出てきた案(ググった)としては、eslintに下記を追加して警告自体をなくす、というものです

rules: {
  'react/prop-types': 'off'
}

当然こちらで実装することは可能なのですが、TypeScriptを利用していて、わざわざその恩恵を排除するというのはチーム開発上選択でいないのでこちらはなしにしました

そして次に見つけたのが記事

this is a page in nextjs and the same error appear in my components too.

the problem is that eslint can’t understand the prop interface when I’m using arrow function.

https://github.com/jsx-eslint/eslint-plugin-react/issues/2777#issuecomment-683555883

通常のReact.FC等ではeslintが解析できていますが、NextjsになるとNextjsの型を認識することができず、それが問題となって、Propsを入れているけどそれをeslintが認識できていない、という状況に陥っていたっぽいです

なのでこのように明示的に型を追加することで対処してみたところ、eslintの警告はなくなり、綺麗に実装することができました!

Cloud Formationでcreate stackするとTemplate format error: unsupported structureが出る

Cloud Formationをcreate stackしたところタイトルのエラーが発生しました

% aws cloudformation create-stack --capabilities CAPABILITY_IAM --stack-name ecs-core-infrastructure --template-body ./ecs-setup/1_Core-infrastructure-setup/core-infrastructure-setup.yml

You must specify a region. You can also configure your region by running "aws configure".

エラー発生してから確認したところ、上記画像のようにエラーが発生していたのでlspで設定を追加しようかなと思っていたのですが、よくよく考えたら、vim上のエラーはあくまでも設定上エラーとして表現されている、と思い諸々調べていたところ、下記のような有益が情報を得られました

The --template-body argument must be specified as a file URI.

https://stackoverflow.com/questions/41992569/template-format-error-unsupported-structure-seen-in-aws-cloudformation

簡単に説明すると、–template-bodyはfile URIとして呼び出さないといけません、ということみたいです

なのでこちらで実行

% aws cloudformation create-stack --capabilities CAPABILITY_IAM --stack-name ecs-core-infrastructure --template-body file://./ecs-setup/1_Core-infrastructure-setup/core-infrastructure-setup.yml


{
    "StackId": "arn:aws:cloudformation:ap-northeast-1:hogehoge:stack/ecs-core-infrastructure/hogehogehogehogehogehogehogehoge"
}

動きました!

参考記事

引用部分に記載してあります

docker + rails + capybaraでSelenium::WebDriver::Error::UnknownError

dockerでRailsのcapybaraテストをjs trueで実装したところ、タイトルのエラーが発生しました

とりあえずこちらが実行した手順

# まずはdockerのプロセス出す
docker ps

# 該当のコンテナを見つけて下記のようにweb_1の場所に記述
docker exec -it web_1 /bin/bash

# 入ったら下記のコマンド(google-chrome)を打ち込み、chromeの状態を調べる
root@cb7713727f8b:/app# google-chrome
[27:27:0428/113240.201687:ERROR:zygote_host_impl_linux.cc(90)] Running as root without --no-sandbox is not supported. See https://crbug.com/638180.

実行したところ–no-sandboxがつけてください、とのことなので下記のようにchrome driverに設定つけて実行してみます

すると下記のようにエラーが出てきました

root@4cde53c2b35e:/app# google-chrome --version
Google Chrome 101.0.4951.41
root@4cde53c2b35e:/app# google-chrome --headless --no-sandbox
qemu: uncaught target signal 5 (Trace/breakpoint trap) - core dumped
qemu: uncaught target signal 5 (Trace/breakpoint trap) - core dumped
[0428/122431.553682:ERROR:bus.cc(398)] Failed to connect to the bus: Failed to connect to socket /run/dbus/system_bus_socket: No such file or directory
[0428/122431.566936:ERROR:file_path_watcher_linux.cc(321)] inotify_init() failed: Function not implemented (38)
[0428/122431.570218:ERROR:bus.cc(398)] Failed to connect to the bus: Failed to connect to socket /run/dbus/system_bus_socket: No such file or directory
qemu: unknown option 'type=utility'
[

下記の記事を調べてみたところ、

wsl上でheadless chrome を起動すると Failed to connect to the bus: Failed to connect to socket /var/run/dbus/system_bus_socket: No such file or directory

こちらのコマンドを実行すると良い、とのことなので実行

/etc/init.d/dbus start

そしてもう一度chrome driverを実行したところ、上記のエラーは解決できて新たにエラーが出現

root@4cde53c2b35e:/app# google-chrome --headless --no-sandbox
qemu: uncaught target signal 5 (Trace/breakpoint trap) - core dumped
qemu: uncaught target signal 5 (Trace/breakpoint trap) - core dumped
[0428/122811.053535:ERROR:file_path_watcher_linux.cc(321)] inotify_init() failed: Function not implemented (38)
qemu: unknown option 'type=utility'
[0428/122811.199162:WARNING:bluez_dbus_manager.cc(248)] Floss manager not present, cannot set Floss enable/disable.
[0428/122811.200983:ERROR:gpu_process_host.cc(968)] GPU process launch failed: error_code=1002
[0428/122811.201179:WARNING:gpu_process_host.cc(1279)] The GPU process has crashed 1 time(s)
[0428/122811.245122:ERROR:network_service_instance_impl.cc(978)] Network service crashed, restarting service.
qemu: unknown option 'type=utility'
[0428/122811.384215:ERROR:gpu_process_host.cc(968)] GPU process launch failed: error_code=1002
[0428/122811.384293:WARNING:gpu_process_host.cc(1279)] The GPU process has crashed 2 time(s)
[0428/122811.392197:ERROR:network_service_instance_impl.cc(978)] Network service crashed, restarting service.
qemu: unknown option 'type=utility'
[

上記のエラーを調べている途中で問題判明

M1ではchrome driverのbuildがないっぽいので、railsが格納しているコンテナのDockerfile自体がダメぽいです

https://zenn.dev/kenkenlysh/articles/78c1797b830053

M1 mac上のDockerコンテナ内でChromiumを動かそうとしてやったこと&やろうとしてること

ただ、M1用のimageもあるので、こちらを別でコンテナ作って、繋げてあげればいけるとのこと

なので、別コンテナ作成

# Dockerfile
chrome:
    // M1 dockerでも使えるやつ
    image: seleniarm/standalone-chromium
    ports:
      - '4444:4444'
web: &web
    // 省略
    environment:
      //こちら追加
      SELENIUM_DRIVER_URL: http://chrome:4444/wd/hub

# spec/supports/capybara.rb
Capybara.register_driver :remote_chrome do |app|
  url = ENV['SELENIUM_DRIVER_URL']
  caps = ::Selenium::WebDriver::Remote::Capabilities.chrome(
    'goog:chromeOptions' => {
      'args' => [
        'no-sandbox',
        'headless',
        'disable-gpu',
        'window-size=1680,1050'
      ]
    }
  )
  Capybara::Selenium::Driver.new(app, browser: :remote, url: url, desired_capabilities: caps)
end

RSpec.configure do |config|
  config.before(:each) do |example|
    if %i[system feature].include?(example.metadata[:type])
      if example.metadata[:js]
        Capybara.server_host = IPSocket.getaddress(Socket.gethostname)
        Capybara.app_host = "http://#{Capybara.server_host}"
        driven_by :remote_chrome
      else
        driven_by :rack_test
      end
    end
  end
end

これでM1 macでもchrome driver動かせました!

Carrierwaveの画像をFile Objectに変換する方法

Carrierwaveに登録した画像を別のモデルに移行するために変換試みたのですが、意外に時間を使ってしまったので次回のために記事にしました

こちら結論

File.binwrite(Rails.root.join("public/#{file.filename}"), file.read)
p.image = File.open(Rails.root.join("public/#{file.filename}"))

1行で一発変換を探していたのですが、無理そうだったのでまずは登録している画像をfileとして保存してます

その際にpathだと正確に画像を取得できない場合もあった(local/prodの違い等)ので、Carrierwaveで保存したファイルをバイナリ経由でFile Objectとして作成、その後にファイルをpublic配下に作成してます

File.binwrite(Rails.root.join("public/#{file.filename}"), file.read)

ファイル作成後に、ファイルのpathからFileをnewして新たにCarrierwave経由で新しい場所(任意のカラム等)に保存するようにしてみました

p.image = File.open(Rails.root.join("public/#{filename}"))

この作成方法だと該当するレコード分だけ画像が作成されてしまうので、loopの最後に画像を削除することが必要なのでその点注意が必要です🙌

また、pathもベタガキなので長期的なことを考えると下記のようにまとめるとより運用楽になるかと

# 共通のpathを設定
path = Rails.root.join("public/#{file.filename}")
# バイナリからファイルを生成、保存
File.binwrite(path, file.read)
# pというインスタンスのimageカラムにFile Object追加
p.image = File.open(path)
# 保存完了後にファイルを削除
File.delete(path)

参考記事

自己解決

Uncaught TypeError: Cannot assign to read only property ‘exports’ of object ‘#Object’

Rails + Reactでタイトルのエラーが発生しました

どうやら、commonJSをES modulesで利用しようとしていることが問題らしく、
babel.config.jsに下記のコードを入力したら解決できました

return {
    "sourceType": "unambiguous", // この部分!
    presets: []
}

参考記事

webpack: import + module.exports in the same module caused error

Docker + postgresqlでrole “postgres” does not existエラー

Dockerのpostgresqlを実行したところタイトルのエラーが発生しました

こちらが一番簡単に解決するための手段

version: "3.8"
services:
  db:
    image: postgres:12-alpine
    ports:
      - '5432:5432'
    volumes:
      - postgres:/var/lib/postgresql/data
    environment:
      POSTGRES_DB: hoge_development # ここ!!!!!
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: postgres
      POSTGRES_INITDB_ARGS: "--encoding=UTF-8"
      TZ: "Asia/Tokyo"
      POSTGRES_HOST_AUTH_METHOD: trust

どうやら2015/7/8以降は、

  • User
  • Database

を作成するだけなら、POSTGRES_DBという環境変数を入れるだけで良くなったらしいので、上記で対応しました🙌


But since July 8th, 2015, if all you need is to create a user and database, it is easier to just make use to the POSTGRES_USERPOSTGRES_PASSWORD and POSTGRES_DB environment variables:

https://stackoverflow.com/questions/26598738/how-to-create-user-database-in-script-for-docker-postgres

ちなみにですが、こちらを適用するために

  • Containers
  • Images
  • Volume

を該当箇所全て削除し、dockerのcacheもclearしてから実行しました

削除せずにおこなったところ動かない状態が続いていたので、ご注意ください

参考記事

How to create User/Database in script for Docker Postgres

nimのSPAフレームワークkaraxでhot reloadする方法

Goのairみたいにhot reloadする方法を探していたら、readmeに普通に書いてありました🙌

こちらが実行コマンド👇

karun -w index.nim

色々な記事を見ていたら、

nim c --hotcodereloading:on -d:glfwDLL testgl.nim

などのhotreloadコマンドが多くて参考になりませんでしたが、karunのnimファイルがあったので、確認してみたところガッツリコマンドのオプションに関する記述があったのですぐにいけました

こちら該当のコード(URL: karun.nim)

case op.kind
    of cmdLongOption:
      case op.key
      of "run":
        run = true
        rest = rest.replace("--run ")
      of "css":
        if op.val != "":
          selectedCss = readFile(op.val)
        else:
          selectedCss = css
        rest = rest.substr(rest.find(" "))
      of "ssr":
        ssr = true
        rest = rest.replace("--ssr ")
      else: discard
    of cmdShortOption:
      if op.key == "r":
        run = true
        rest = rest.replace("-r ")
      if op.key == "w": #[ ここ!!!!! ]#
        watch = true
        rest = rest.replace("-w ")
      if op.key == "s":
        ssr = true
        rest = rest.replace("-s ")
    of cmdArgument: file = op.key
    of cmdEnd: break

複数記事で`-r`オプション入れる、などと記載あったので、もしかしたら他にもコマンドあるかも?と思って調べたところ一発で見つかってよかったです

一応他のオプションも見たのですが、SSRも行けるそうなので、まだ調査はできていないのですが、SPAフレームワークとしてガッツリ使用することも悪くない選択肢と思えてきます

数日前からnimを触り始めたので魅力を引き出せきれてないですが、思いのほか書き方が好きなので継続して調査と実装進めていきたいです!

参考記事

https://github.com/karaxnim/karax/blob/master/karax/tools/karun.nim#L32

nimプロジェクトを始めるにあたって

mainファイルを作成してだけだと流石に動かないような?と思って調べてみたところ、nimbleを活用して生成することができることがわかったのでメモとして残します

とりあえず、nimble initして指示に従って入力してプロジェクトを作成します

% nimble init
      Info: Package initialisation requires info which could not be inferred.
        ... Default values are shown in square brackets, press
        ... enter to use them.
      Using "nim" for new package name
      Using masahirookubo for new package author
      Using "src" for new package source directory
    Prompt: Package type?
        ... Library - provides functionality for other packages.
        ... Binary  - produces an executable for the end-user.
        ... Hybrid  - combination of library and binary
        ... For more information see https://goo.gl/cm2RX5
     Select Cycle with 'Tab', 'Enter' when done
    Answer: binary
    Prompt: Initial version of package? [0.1.0]
    Answer:
    Prompt: Package description? [A new awesome nimble package]
    Answer:
    Prompt: Package License?
        ... This should ideally be a valid SPDX identifier. See https://spdx.org/licenses/.
     Select Cycle with 'Tab', 'Enter' when done
    Answer: MIT
    Prompt: Lowest supported Nim version? [1.6.4]
    Answer:
   Success: Package nim created successfully

作成完了すると、テストファイルなども生成されてます

ちなみにですが、nimble initせずにnim製のSPAフレームワークkaraxを使ったときは補完がうまくいかなかったので、nimble initすることでrootとして設定する、とかもやっているかもです

参考記事

Nimble入門

nvim + coc + nim + macOSの環境開発

仕事でGoやほんの少しRustを触る機会があって、近しいnimがだいぶ気になっていたので、環境設定してみました

まずはnimをinstallしていきます


$ curl https://nim-lang.org/choosenim/init.sh -sSf | sh

Switched to Nim 1.6.4
choosenim-init: ChooseNim installed in /Users/masahirookubo/.nimble/bin
choosenim-init: You must now ensure that the Nimble bin dir is in your PATH.
choosenim-init: Place the following line in the ~/.profile or ~/.bashrc file.
choosenim-init:     export PATH=/Users/masahirookubo/.nimble/bin:$PATH

※brew install nimでもinstallできましたが、nimlspをinstallするタイミングで下記エラー出たので、上記でinstallを行っています

Error: cannot open file: /opt/homebrew/Cellar/nim/1.6.4/nim/nimsuggest/nimsuggest.nim

installが完了した環境変数をzshやbashに設置

# .zshrc
export PATH=/Users/masahirookubo/.nimble/bin:$PATH

設置完了したら反映して適用されているかを確認

$source ~/.zshrc
$ which nim
/Users/masahirookubo/.nimble/bin/nim

nimが問題なく設置できているので、次はlspを追加します

$ nimble install nimlsp
Downloading https://github.com/PMunch/nimlsp using git
  Verifying dependencies for nimlsp@0.4.0
      Info: Dependency on jsonschema@>= 0.2.1 already satisfied
  Verifying dependencies for jsonschema@0.2.1
      Info: Dependency on ast_pattern_matching@any version already satisfied
  Verifying dependencies for ast_pattern_matching@1.0.0
 Installing nimlsp@0.4.0
   Building nimlsp/nimlsp using c backend
/private/var/folders/bb/n3dq0s2963v_4c8dw8ygjlgm0000gn/T/nimble_45528/githubcom_PMunchnimlsp/src/nimlsppkg/baseprotocol.nim(26, 29) Warning: Deprecated since 1.5; TaintedString is deprecated [Deprecated]
   Success: nimlsp installed successfully.

lspが追加できたらcocの設定を行います

"nim": {
  "command": "nimlsp",
  "filetypes": ["nim"],
  "trace.server": "verbose"
}

lspの設定を行ってもnimファイルを認識しないことがあるので、私はこちらをvimrcに追加して強制的に認識させました

autocmd BufNewFile,BufRead *.nim, set filetype=nim

lsp入れ終わったので、一旦確認

型定義を表示できたので、一応これで開発はできそうです!

ガッツリ開発もしてみたいので、シンタックスも入れてみます

[[plugins]]
repo = 'baabelfish/nvim-nim'
on_ft = ['nim']

入れ終わるとこんな感じでシンタックス適用できて、かなりみやすくなりました!

参考記事

VimでのNim開発環境構築

NeovimでNimを書く環境を整える

jestで全てpassなのにexit status1が出る

jestで全てのtestをpassしているにもかかわらず、なぜかexit status1が出る、という問題が発生しました

Test Suites: 55 passed, 55 total
Tests:       402 passed, 402 total
Snapshots:   3 obsolete, 20 passed, 20 total
Time:        71.287 s
Ran all test suites.
error Command failed with exit code 1.

どうやらobsoleteが悪さをしているらしく、こちらのコマンドでobsoleteを解消することでpassさせることができます

※ -u を追加

yarn test --coverage -w 1 -u

-u コマンドは失敗したsnapshotテストを再生成するための指定で、残っているsnapshotなどに悪ささせないことが可能となっています

ちなみにですが、CI上では-uを付けると問題になることがあるみたいなので、あまりよろしくないそうです

https://github.com/facebook/jest/issues/9324#issuecomment-623713377

参考記事

【Jest】テストは全てsuccessなのにexit statusが 1

JEST tests complete successfully but returns exit status 1 #9324