眠気.jl

投稿=不定期

hyper-tlsでHTTPSリクエスト(not HTTP)する備忘録

経緯

DMM APIHTTPSリクエストしか許してくれず、かと言ってhyperでhttpsリクエストしようとすると

StringError("Invalid scheme for Http")

なのでhyper-tlsいれてリクエスト飛ばして解決しました

手順

Cargo.toml追記

hyper = { version = "0.14.23", features = ["full"] }
tokio = { version = "1.22.0", features = ["full"] }
hyper-tls = { version = "0.5.0" }

src/main.rs

use hyper::{body::HttpBody as _, Client};
use hyper_tls::HttpsConnector;
use tokio::io::{self, AsyncWriteExt as _};

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let https = HttpsConnector::new();
    let client = Client::builder().build::<_, hyper::Body>(https);

    let mut res = client.get("https://api.dmm.com/affiliate/v3/ItemList?api_id=[app_Id]&affiliate_id=[affiliate_id]&site=FANZA&service=digital&floor=videoa&hits=10&sort=date&keyword=%e4%b8%8a%e5%8e%9f%e4%ba%9c%e8%a1%a3&output=json".parse()?).await?;

    println!("Status: {}", res.status());
    println!("Headers:\n{:#?}", res.headers());

    while let Some(chunk) = res.body_mut().data().await {
        let chunk = chunk?;
        io::stdout().write_all(&chunk).await?
    }
    Ok(())
}

参考

hyper-tls/client.rs at master · hyperium/hyper-tls · GitHub

YewでHelloWorld: 備忘録

Yew動かすまでにやったことすべてのメモ

cargo new yewexample
cd yewexample
touch index.html
cargo install --locked trunk

Cargo.toml追記

yew = { git = "https://github.com/yewstack/yew/", features = ["csr"]}

src/main.rsの編集

use yew::prelude::*;

#[function_component(App)]
fn app() -> Html {
    html! {
        <div>
        <h1>{ "Hello World" }</h1>
        <h2>{ "HellowWorld2" }</h2>
        </div>
    }
}

fn main() {
    yew::Renderer::<App>::new().render();
}
trunk serve --release

8080で確認

終わりに

WebGLのexampleとかもあるので面白そうだなとなってます

yew/examples at master · yewstack/yew · GitHub

sqlboilerでsupabaseから構造体生成した: 備忘録

models_psqlフォルダに構造体を生成する

インストール

go install github.com/volatiletech/sqlboiler/v4@v4.13.0
go install github.com/volatiletech/sqlboiler/v4/drivers/sqlboiler-psql@v4.13.0

sqlboiler.toml

[psql]
  dbname = "postgres"
  host   = "db.プロジェクトID.supabase.co"
  port   = 5432
  user   = "postgres"
  pass   = "自分のパスワード"
  sslmode = "disable"
  schema = "public"
  blacklist = ["migrations", "other"]

構造体生成

sqlboiler psql --output models_psql --pkgname models_psql --wipe

AWS CDK 2.47.0でDynamoDBの作成: 備忘録

準備

npm i -g aws-cdk
npm i @aws-cdk/aws-dynamodb

実行

mkdir fanzamodb
cd fanzamodb
cdk init sample-app --language=typescript

lib/fanzamodb-stack.tsを編集

import * as dynamodb from "aws-cdk-lib/aws-dynamodb";
import { Duration, Stack, StackProps, RemovalPolicy } from "aws-cdk-lib";
import { Construct } from "constructs";
import * as lambda from "@aws-cdk/aws-lambda";

export class FanzamodbStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);
    const table = new dynamodb.Table(this, "Table", {
      partitionKey: { name: "id", type: dynamodb.AttributeType.STRING },
      billingMode: dynamodb.BillingMode.PROVISIONED,
      readCapacity: 20,
      writeCapacity: 20,
      removalPolicy: RemovalPolicy.DESTROY,
      sortKey: { name: "createdAt", type: dynamodb.AttributeType.NUMBER },
      pointInTimeRecovery: true,
      tableClass: dynamodb.TableClass.STANDARD_INFREQUENT_ACCESS,
    });

    table.addLocalSecondaryIndex({
      indexName: "statusIndex",
      sortKey: { name: "status", type: dynamodb.AttributeType.STRING },
      projectionType: dynamodb.ProjectionType.ALL,
    });

    const readScaling = table.autoScaleReadCapacity({
      minCapacity: 1,
      maxCapacity: 50,
    });

    readScaling.scaleOnUtilization({
      targetUtilizationPercent: 50,
    });

    const globalTable = new dynamodb.Table(this, "Table", {
      partitionKey: { name: "id", type: dynamodb.AttributeType.STRING },
      replicationRegions: ["us-east-1", "us-east-2", "us-west-1"],
      billingMode: dynamodb.BillingMode.PROVISIONED,
      replicationTimeout: Duration.hours(3),
    });
    globalTable
      .autoScaleWriteCapacity({
        minCapacity: 1,
        maxCapacity: 10,
      })
      .scaleOnUtilization({ targetUtilizationPercent: 75 });
  }
}
cdk deploy

確認

AWSコンソール->DynamoDB->リージョン ["us-east-1", "us-east-2", "us-west-1"]それぞれにテーブルが作成されていることを確認

Stripeの契約ダッシュボードをNext.jsに埋め込む :備忘録

Stripe側の準備

userにmanage subscriptionの権限を付与しておく
与えたい契約の選択肢を追加しておく

ページ側

  const router = useRouter();
  const loadPortal = async () => {
    const { data } = await axios.get("/api/portal");
    router.push(data.url);
  };
  return (
    <div>
      <button onClick={loadPortal}>サブスクの管理ページにジャンプする</button>
    </div>
  );

api

    const session = await stripe.billingPortal.sessions.create({
      customer: stripe_customer, // stripeのcustomer.id
      return_url: http://localhost:3000, // dev
    });
    res.send({
      url: session.url,
    });