[컴] gatsby 의 createPages, createResolvers

 gatsbyjs / 개츠비 / api / 게츠비

gatsby 의 createPages, createResolvers

createPages, createResolvers 2개의 함수는 gatsby-node.js 에 정의된다.

createPages[ref. 1]

gatsby-node.js 에서 createPages를 export 하면 page를 생성할 수 있다. static page 들을 programatically 하게 만들어낼 수 있다. 아래 product 같은 경우를 보면, product 가 여러개 있을 때, 각 product 마다 static page 를 만들어주게 할 수 있다. createPage를 loop 돌려서.

exports.createPages = async ({ graphql, actions }) => {
    // page 생성 1
    createPage({
      path: `/collection/${collection.slug}`,
      component: require.resolve("./src/templates/collection.tsx"),
      context: {
        collection,
        products,
        childCollections,
      },
      defer: false,
    })
    ...
    // page 생성 2
    createPage({
      path: `/product/${product.slug}`,
      component: require.resolve("./src/templates/product.tsx"),
      context: {
        product,
      },
      defer: false,
    })
}

creatResolvers[ref.2]

아래 예제에서 Vendure_Asset 은 Vendure 의 Asset type 을 이야기한다.

그래서 아래 createResolversVendure_Asset graphQL 에 imageFile을 추가하겠다.라는 뜻이다.

exports.createResolvers = ({
  actions,
  cache,
  createNodeId,
  createResolvers,
  store,
  reporter,
}) => {
  const { createNode } = actions
  createResolvers({
    Vendure_Asset: {
      imageFile: {
        type: `File`,
        resolve(source, args, context, info) {
          const url = new URL(source.preview).href;
          return createRemoteFileNode({
            url,
            store,
            cache,
            createNode,
            createNodeId,
            reporter,
          })
        },
      },
    },
    Vendure_SearchResultAsset: {
      imageFile: {
        type: `File`,
        resolve(source, args, context, info) {
          return createRemoteFileNode({
            url: source.preview,
            store,
            cache,
            createNode,
            createNodeId,
            reporter,
          })
        },
      },
    },
  })
}

그래서 아처럼 graphQL 에서 Asset type 에 imageField 가 추가된다.

const GET_COLLECTIONS = /* GraphQL */ `
  query {
    vendure {
      collections {
        items {
          id
          name
          description
          slug
          breadcrumbs {
            id
            name
            slug
          }
          featuredAsset {
            id
            preview
            imageFile {
              childImageSharp {
                gatsbyImageData(width: 300, height: 300, quality: 85)
              }
            }
          }
          parent {
            id
            name
          }
        }
      }
    }
  }
`

References

  1. Creating and Modifying Pages | Gatsby
  2. creatResolvers | Gatsby Node APIs | Gatsby

[컴] gatsby js 에서 server side rendering 하는 page 생성

 

게츠비 / 개츠비 / ssr / gatsbyjs / getsbyjs

gatsby js 에서 server side rendering 하는 page 생성

  1. export async function getServerData 가 있어야만 한다.
  2. return 에 props로 보내는 값이 serverData로 넘어가게 된다.
import * as React from "react"
import { Link } from "gatsby"

import Layout from "../components/layout"
import Seo from "../components/seo"

const PageSSR = ({ serverData }) => {
  return (
    <div>
      <h1>SSR page</h1>
      <img
        alt="A random dog"
        src={serverData.message}
      />
      <Link to="/">Go back to the homepage</Link>
    </div>
  )
}

export default PageSSR

export async function getServerData() {
  try {
    const res = await fetch(`https://dog.ceo/api/breeds/image/random`)
    if (!res.ok) {
      throw new Error(`Response failed`)
    }
    return {
      props: await res.json(),
    }
  } catch (error) {
    return {
      status: 500,
      headers: {},
      props: {},
    }
  }
}

References

  1. Server-Side Rendering API | Gatsby

[컴] vendure gatsby storefront build

 

storefront / 개츠비 / 게츠비 client / gatsbyjs client / gatsby

vendure gatsby storefront build

다음 vendure 의 gatsby storefront 를 빌드해 보려 한다.

  1. .env.production을 만들어서 넣는다. ini GATSBY_VENDURE_SHOP_API_URL=https://readonlydemo.vendure.io/shop-api
  2. npm run build 를 하면 gatsby build가 실행된다. build 를 완료하면, /public에 page들이 만들어진다. 그외 다른 file 들도 /public folder에 만들어진다.

vendure storefront 띄우기(gatsby)

빌드와 비슷하다.

  1. .env.production 만들기
    • npm run build(gatsby build) : 이를 실행하면, .env.production 을 사용한다.
    • npm run develop(gatsby develop --inspect) : 바로 빌드하고, 서버를 띄워준다. --inspect option 으로.
    • npm run start(gatsby develop) : 바로 빌드하고, 서버를 띄워준다.
    • npm run serve(gatsby serve)
npm run build

build 가 되고나며, 어떤 것이 SSG 인지, SSR 인지 알 수 있다. (그림참고)


D:\gatsby-starter>npm run build    

> gatsby-starter-default@0.1.0 build
> gatsby build

success compile gatsby files - 1.483s
success load gatsby config - 0.034s
success load plugins - 0.673s
success onPreInit - 0.008s
success initialize cache - 0.101s
success copy gatsby files - 0.280s
success Compiling Gatsby Functions - 0.331s
success onPreBootstrap - 0.350s
success createSchemaCustomization - 2.025s
success Checking for changed pages - 0.002s
success source and transform nodes - 0.354s
info Writing GraphQL type definitions to
D:/gatsby-starter/.cache/schema.gql
success building schema - 0.481s
⠇ createPages
...
⠸ createPages
⠴ createPages
success createPages - 123.379s
success compile gatsby files - 1.483s
success load gatsby config - 0.034s
success load plugins - 0.673s
success onPreInit - 0.008s
success initialize cache - 0.101s
success copy gatsby files - 0.280s
success Compiling Gatsby Functions - 0.331s
success onPreBootstrap - 0.350s
success createSchemaCustomization - 2.025s
success Checking for changed pages - 0.002s
success source and transform nodes - 0.354s
info Writing GraphQL type definitions to
D:/gatsby-starter/.cache/schema.gql
success building schema - 0.481s
success createPages - 123.379s
success createPagesStatefully - 0.075s
info Total nodes: 222, SitePage nodes: 70 (use --verbose for breakdown)
success Checking for changed pages - 0.002s
success Cleaning up stale page-data - 0.004s
success onPreExtractQueries - 0.002s
success extract queries from components - 1.766s
success write out redirect data - 0.003s
success Build manifest and related icons - 0.148s
success onPostBootstrap - 0.157s
info bootstrap finished - 134.671s
success write out requires - 0.010s
success Building production JavaScript and CSS bundles - 9.858s
success Building Rendering Engines - 24.734s
success Building HTML renderer - 10.259s
success Execute page configs - 0.044s
success Validating Rendering Engines - 1.869s
success Caching Webpack compilations - 0.002s
success run queries in workers - 1.030s - 73/73 70.87/s
success Running gatsby-plugin-sharp.IMAGE_PROCESSING jobs - 170.795s - 237/237 1.39/s
success Merge worker state - 0.003s
success Rewriting compilation hashes - 0.002s
success Writing page-data.json files to public directory - 0.020s - 69/70 3502.40/s
success Building static HTML for pages - 4.962s - 69/69 13.90/s
success onPostBuild - 0.004s
success compile gatsby files - 1.483s
success load gatsby config - 0.034s
success load plugins - 0.673s
success onPreInit - 0.008s
success initialize cache - 0.101s
success copy gatsby files - 0.280s
success Compiling Gatsby Functions - 0.331s
success onPreBootstrap - 0.350s
success createSchemaCustomization - 2.025s
success Checking for changed pages - 0.002s
success source and transform nodes - 0.354s
info Writing GraphQL type definitions to
D:/gatsby-starter/.cache/schema.gql
success building schema - 0.481s
success createPages - 123.379s
success createPagesStatefully - 0.075s
info Total nodes: 222, SitePage nodes: 70 (use --verbose for breakdown)
success Checking for changed pages - 0.002s
success Cleaning up stale page-data - 0.004s
success onPreExtractQueries - 0.002s
success extract queries from components - 1.766s
success write out redirect data - 0.003s
success Build manifest and related icons - 0.148s
success onPostBootstrap - 0.157s
info bootstrap finished - 134.671s
success write out requires - 0.010s
success Building production JavaScript and CSS bundles - 9.858s
success Building Rendering Engines - 24.734s
success Building HTML renderer - 10.259s
success Execute page configs - 0.044s
success Validating Rendering Engines - 1.869s
success Caching Webpack compilations - 0.002s
success run queries in workers - 1.030s - 73/73 70.87/s
success Running gatsby-plugin-sharp.IMAGE_PROCESSING jobs - 170.795s - 237/237 1.39/s
success Merge worker state - 0.003s
success Rewriting compilation hashes - 0.002s
success Writing page-data.json files to public directory - 0.020s - 69/70 3502.40/s
success Building static HTML for pages - 4.962s - 69/69 13.90/s
success onPostBuild - 0.004s
info Done building in 189.1672697 sec
success compile gatsby files - 1.483s
success load gatsby config - 0.034s
success load plugins - 0.673s
success onPreInit - 0.008s
success initialize cache - 0.101s
success copy gatsby files - 0.280s
success Compiling Gatsby Functions - 0.331s
success onPreBootstrap - 0.350s
success createSchemaCustomization - 2.025s
success Checking for changed pages - 0.002s
success source and transform nodes - 0.354s
info Writing GraphQL type definitions to
D:/gatsby-starter/.cache/schema.gql
success building schema - 0.481s
success createPages - 123.379s
success createPagesStatefully - 0.075s
info Total nodes: 222, SitePage nodes: 70 (use --verbose for breakdown)
success Checking for changed pages - 0.002s
success Cleaning up stale page-data - 0.004s
success onPreExtractQueries - 0.002s
success extract queries from components - 1.766s
success write out redirect data - 0.003s
success Build manifest and related icons - 0.148s
success onPostBootstrap - 0.157s
info bootstrap finished - 134.671s
success write out requires - 0.010s
success Building production JavaScript and CSS bundles - 9.858s
success Building Rendering Engines - 24.734s
success Building HTML renderer - 10.259s
success Execute page configs - 0.044s
success Validating Rendering Engines - 1.869s
success Caching Webpack compilations - 0.002s
success run queries in workers - 1.030s - 73/73 70.87/s
success Running gatsby-plugin-sharp.IMAGE_PROCESSING jobs - 170.795s - 237/237 1.39/s
success Merge worker state - 0.003s
success Rewriting compilation hashes - 0.002s
success Writing page-data.json files to public directory - 0.020s - 69/70 3502.40/s
success Building static HTML for pages - 4.962s - 69/69 13.90/s
success onPostBuild - 0.004s
info Done building in 189.1672697 sec
success compile gatsby files - 1.483s
success load gatsby config - 0.034s
success load plugins - 0.673s
success onPreInit - 0.008s
success initialize cache - 0.101s
success copy gatsby files - 0.280s
success Compiling Gatsby Functions - 0.331s
success onPreBootstrap - 0.350s
success createSchemaCustomization - 2.025s
success Checking for changed pages - 0.002s
success source and transform nodes - 0.354s
info Writing GraphQL type definitions to
D:/gatsby-starter/.cache/schema.gql
success building schema - 0.481s
success createPages - 123.379s
success createPagesStatefully - 0.075s
info Total nodes: 222, SitePage nodes: 70 (use --verbose for breakdown)
success Checking for changed pages - 0.002s
success Cleaning up stale page-data - 0.004s
success onPreExtractQueries - 0.002s
success extract queries from components - 1.766s
success write out redirect data - 0.003s
success Build manifest and related icons - 0.148s
success onPostBootstrap - 0.157s
info bootstrap finished - 134.671s
success write out requires - 0.010s
success Building production JavaScript and CSS bundles - 9.858s
success Building Rendering Engines - 24.734s
success Building HTML renderer - 10.259s
success Execute page configs - 0.044s
success Validating Rendering Engines - 1.869s
success Caching Webpack compilations - 0.002s
success run queries in workers - 1.030s - 73/73 70.87/s
success Running gatsby-plugin-sharp.IMAGE_PROCESSING jobs - 170.795s - 237/237 1.39/s
success Merge worker state - 0.003s
success Rewriting compilation hashes - 0.002s
success Writing page-data.json files to public directory - 0.020s - 69/70 3502.40/s
success Building static HTML for pages - 4.962s - 69/69 13.90/s
success onPostBuild - 0.004s
info Done building in 189.1672697 sec


Pages

┌ src/templates/collection.tsx
│ ├   /collection/electronics
│ └   ...8 more pages available
├ src/templates/product.tsx
│ ├   /product/laptop
│ └   ...53 more pages available
├ src/pages/404.tsx
│ ├   /404/
│ └   /404.html
├ src/pages/about.tsx
│ └   /about/
├ src/pages/index.tsx
│ └   /
├ src/pages/search.tsx
│ └   /search/
├ src/pages/using-ssr.tsx
│ └ ∞ /using-ssr/
└ src/pages/using-typescript.tsx
  └   /using-typescript/

  ╭────────────────────────────────────────────────────────────────╮
  │                                                                │
  │   (SSG) Generated at build time                                │
  │ D (DSG) Deferred static generation - page generated at runtime │
  │ ∞ (SSR) Server-side renders at runtime (uses getServerData)    │
  │ λ (Function) Gatsby function                                   │
  │                                                                │
  ╰────────────────────────────────────────────────────────────────╯

Reference

  1. Create a New React App – React
  2. Porting from Create React App to Gatsby | Gatsby

[컴] gatsbyjs debugging

gatsby / 개츠비 / 디버깅 / debug

gatsbyjs debugging

아래처럼 debugger 를 attach 할 수 있다.

Gatsby develop을 실행하고, server-side rendering(SSR) 관련 file 에 breakpoint 를 찍으면, 해당 page 가 사용될 때 break 된다.

client side rendering code 에 대한 debug

이것은 chrome debugging tool 을 사용하면 된다. 일반적인 다른 react app 을 debug 할 때 처럼 하면 된다.

server side rendering code 에 대한 debug

vscode debugger 설정

  • 자동설정
    • vscode 의 setting 에 가서 ‘node debug’를 ’auto attach’ 로 설정 -실행
      • gatsby develop –> node --nolazy node_modules/.bin/gatsby develop --inspect-brk
      • gatsby build –> node --nolazy --inspect-brk node_modules/.bin/gatsby build
  • 수동설정: vscode 의 launch.json을 아래처럼 설정하고, debugger를 실행한다.

windows launch.json :

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Gatsby develop",
      "type": "pwa-node",
      "request": "launch",
      "program": "${workspaceRoot}/node_modules/.bin/gatsby",
      "windows": {
        "program": "${workspaceRoot}/node_modules/gatsby/dist/bin/gatsby"
      },
      "args": ["develop"],
      "env": {
        "PARCEL_WORKERS": "0",
        "GATSBY_CPU_COUNT": "1",
      },
      "runtimeArgs": ["--nolazy"],
      "console": "integratedTerminal"
    },
    {
      "name": "Gatsby build",
      "type": "pwa-node",
      "request": "launch",
      "program": "${workspaceRoot}/node_modules/.bin/gatsby",
      "windows": {
        "program": "${workspaceRoot}/node_modules/gatsby/dist/bin/gatsby"
      },
      "args": ["build"],
      "env": {
        "PARCEL_WORKERS": "0",
        "GATSBY_CPU_COUNT": "1",
      },
      "runtimeArgs": ["--nolazy"],
      "console": "integratedTerminal"
    }
  ]
}

References

  1. Debugging the Build Process | Gatsby

[컴] jenkins plugin 업데이트 전에 해야할일

jenkins plugin 업데이트 실패시 복구 / 젠킨스 플러그인 업데이트 방법

jenkins plugin 업데이트 전에 해야할일

젠킨스 플러그인을 업데이트 하려면 미리 plugin folder를 백업해 놓자.

젠킨스 플러그인 업데이트 하다가 restart 가 안되는 경우 plugin directory 만 이전으로 돌려주면 다시 돌려놓을 수 있다.

[컴] espanso, text 확장기

copilot / 코딩 / suggest / candidate / 예상 / text expander

espanso, text 확장기

설치

설명

이것은 bash 의 alias 와 비슷하다. 다만 차이점은 bash 의 alias 는 bash 내에서만 된다. 즉, command line 에서만 쓰인다.

하지만 이것은 gui 에서 쓰인다. 그래서 windows 내의 모든 application 안에 있는 typing 영역에서 사용할 수 있다. (예를 들면, 콘솔창, 텍스트 에디터, 웹브라우저의 주소창등.)

그래서 typing 을 줄여줄 수 있다. coding 에서 쓰는 snippet 과 같은 동작도 지원해주고, shell 에서 실행한 결과를 text 로 가져오고 싶다면 그런 것도 지정해 놓을 수 있다.

base.yml 에 자신이 원하는 command 를 추가해 놓을 수 있다.

  • %appdata%\espanso\match\base.yml

community

package

espanso 는 package를 제공한다.

설치된 package list 를 보여준다

espansod.exe package list

예시

아래처럼 해놓으면, :s2 를 typing 할 때마다, console 에서 dir 해서 나온 결과값이 화면에 typing 이 된다.

matches:
  ...
  - trigger: ":s2"
    replace: "{{output}}"
    vars:
      - name: output
        type: shell
        params:
          cmd: "dir"

  - trigger: ":ip"
    replace: "{{output}}"
    vars:
      - name: output
        type: shell
        params:
          cmd: "curl https://api.ipify.org"
          shell: cmd

toggle key

default.yml 에 가서 toogle_key 를 설정하면 된다.

  • %appdata%\espanso\config\default.yml

만약 ‘ALT’ 로 설정했다면, ’ALT’key 를 두번 누르는 경우 espanso 가 동작하지 않게 된다.

search bar key

default.yml 에 가서 search_shortcut 를 설정하면 된다.

search_shortcut: ALT+SHIFT+SPACE

특정 app 에서 disable

특정 app 이 실행될때 espanso 를 disable 시킬 수 도 있다.

include, exclude 규칙

_mymatch.yml 처럼 앞에 _를 붙이면, espanso 가 자동으로 load 하지 않는다.

debugging

log 보기

문제가 발생할 때 log 를 보려면 다음처럼 하면 된다.

espansod.exe log

debug: true

  - trigger: ":localip"
    replace: "{{output}}"
    vars:
      - name: output
        type: shell
        params:
          cmd: "ip a | grep 'inet 192' | awk '{ print $2 }'"
          debug: true

windows 에서 주의할 점

만약 espanso 를 일반 사용자 계정으로 실행한다면, ‘관리자’(administrator) 계정으로 실행한 app 안에서는 동작하지 않는다.

example

  • %appdata%.yml
# espanso match file
matches:

  - trigger: ":ip"
    replace: "{{output}}"
    vars:
      - name: output
        type: shell
        params:
          cmd: "curl https://api.ipify.org"
          shell: cmd

  - trigger: ":dbdump"
    replace: "mysqldump --databases mydb -h locahost -u myuserid -P 3306 -p > rds-mydb.sql"
  - trigger: ":dbinsert"
    replace: "chcp 65001 && \"mysql.exe\" -u root -p mydb < rds-mydb.sql"

  - trigger: ":cutf"
    replace: "chcp 65001"

  # markdown
  - trigger: ":img"
    replace: "![]('{{clipboard}}')"
    vars:
      - name: "clipboard"
        type: "clipboard"
  # markdown
  - trigger: ":ref"
    replace: "## References\n"

  # run an app
  - trigger: ":espanso-config"
    replace: "{{output}}"
    vars:
      - name: output
        type: shell
        params:
          cmd: "c:\\Program Files\\Sublime Text 3\\sublime_text.exe"
          shell: cmd

  - trigger: ":run-sublimetext"
    replace: "{{output}}"
    vars:
      - name: output
        type: shell
        params:
          cmd: "c:\\Program Files\\Sublime Text 3\\sublime_text.exe"
          shell: cmd

  - trigger: ":run-lnk"
    replace: "{{output}}"
    vars:
      - name: output
        type: shell
        params:
          cmd: "c:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\7-Zip\\7-Zip File Manager.lnk"
          shell: cmd
  # message 를 받는 form 을 보여준다.
  - trigger: ":git-commit"
    form: |
      'git commit -m "[[message]]"'
  # cmd /v 가 필요
  - trigger: ":git-bcopy"
    replace: |
              for /f "delims=" %a in ('git --no-pager branch ^| d:\a\apps\fzf\fzf.exe +m') do @set branch=%a && echo !branch:~2,-1! | clip
  - trigger: ":git-cbranch"
    replace: |
              for /f "delims=" %a in ('git --no-pager branch ^| d:\a\apps\fzf\fzf.exe +m') do @set branch=%a && git checkout !branch:~2,-1!

  # 여러파일중 하나를 선택하는 예시
  - trigger: ":file"
    replace: "{{form1.file}}"
    vars:
      - name: files
        type: shell
        params:
          cmd: "dir /b ."
          shell: cmd
      - name: form1
        type: form
        params:
          layout: |
            Select file:
            [[file]]
          fields:
            file:
              type: list
              values: "{{files}}"
  # And much more! For more information, visit the docs: https://espanso.org/docs/

See Also

  1. 쿠…sal: [컴][유틸] fzf - fuzzy finder
  2. Speed up git commands with Autohotkey - DEV Community : autohotkey 로 espanso 와 비슷한 효과를 낼 수 있다. 
  3. 쿠...sal: [컴] espanso, text 확장기, 내설정
  4. Hotkeys & Text Expander | 500+ Productivity Resources : 다른 extender 들을 확인할 수 있다.

[컴] jenkins 에서 gittea gogs webhook 사용법

gittea 와 jenkins 연결 / gogs commit 시 jenkins 구동 / build 시작 / ci / commit 시 자동 시작

jenkins 에서 gittea gogs webhook 사용법

간략하게 설명하면 다음 2가지를 하면 된다.

  1. git repository 에서 commit 이 되면, commit 이 됐다는 신호를 webhook 방식으로 jenkins 에 보내주면 된다.
  2. 그리고 jenkins 에는 webhook 을 사용할 것이니 받을 준비하고 있어라라고 설정해주면 된다.

위 이야기를 좀 더 자세히 해보자.

webhook 설정

각 regpository 마다 webhook 설정 UI 가 조금 다르지만, gittea는 github 와 유사하다.

  • “repository –> Settings –> Webhooks –> Add Webhook –> Gogs” 을 하면 된다.
    • Gittea 를 택해도 된다. request 형식만 맞으면 상관없다.
  • Target URL : jenkins 의 어느 job 에 보낼 것인지를 지정해 준다.
    • http://<jenkins_url>/gogs-webhook/?job=myfolder_name/myjob_name
    • ref.1 에서 보면, gogs-webhook 이라는 url 로 request 를 보내야 한다.
  • Secret
    • 암호를 적어준다. 이 암호는 jenkins 에서 ‘Gogs Webhook’ 설정시 사용하게 된다.
  • Trigger On
    • Push Events 를 선택(이것이 아마도 git push 가 발생할 때 webhook 을 보내겠다는 이야기일 것이다.)
  • Branch filter
    • 어떤 branch 의 push 가 발생했을 때 webhook 을 보낼지 정한다.
    • 예를 들어, master 로 하면 master branch 에 push 가 발생했을 때 webhook 을 jenkins 로 보낸다는 이야기다.
gittea 화면

Jenkins 설정

젠킨스에는 Gogs | Jenkins plugin 이 설치돼 있어야 한다.

그러면 job 을 생성할 때 ‘Gogs Webhook’ tab 이 보인다.

  • ‘Use Gogs secret’ 에 check 하고
  • Secret 에 gittea 에서 설정한 암호를 넣자
젠킨스 화면

test

이제 master branch 에 commit 을 하고 push 를 하면 jenkins 에 신호가 갈 것이다.

참고로, 여기까지는 trigger 를 보내는 것이지, 실제로 build 를 일으키거나 하지 않는다. trigger 가 발생된 이후 작업은 각자가 젠킨스(jenkins)에서 설정하면 된다. 그래서 현재 설정은 master branch 가 push 됐을 때 신호가 가지만, 그 시점에 build 는 develop 등 다른 branch 를 해도 상관없다. 그리고 아마도 Build Triggers 부분에서 'Build when a change is pushed to Gogs' 에 check 를 해줘야 build 가 될 것이다.

See Also

  1. 쿠…sal: [컴] jenkins pipeline 예시

References

  1. gitea and jenkins webhook - Stack Overflow