moved compiled constants into an env.json file (#1051)

This commit is contained in:
Elijah Ahianyo 2023-05-19 17:28:54 +00:00 committed by GitHub
parent 87b5378db2
commit fb69ddfd80
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 43 additions and 38 deletions

View File

@ -5,9 +5,6 @@
{{custom_code}} {{custom_code}}
{% endfor %} {% endfor %}
{% for name, url in endpoints.items() %}
const {{name}} = {{url|json_dumps}}
{% endfor %}
{% endblock %} {% endblock %}
{% block export %} {% block export %}
@ -38,7 +35,7 @@ export default function Component() {
return; return;
} }
if (!{{const.socket}}.current) { if (!{{const.socket}}.current) {
connect({{const.socket}}, {{state_name}}, {{state_name|react_setter}}, {{const.result}}, {{const.result|react_setter}}, {{const.router}}, {{const.event_endpoint}}, {{transports}}) connect({{const.socket}}, {{state_name}}, {{state_name|react_setter}}, {{const.result}}, {{const.result|react_setter}}, {{const.router}}, {{transports}})
} }
const update = async () => { const update = async () => {
if ({{const.result}}.{{const.state}} != null){ if ({{const.result}}.{{const.state}} != null){

View File

@ -0,0 +1,5 @@
{
"compilerOptions": {
"baseUrl": "."
}
}

View File

@ -2,9 +2,11 @@
import axios from "axios"; import axios from "axios";
import io from "socket.io-client"; import io from "socket.io-client";
import JSON5 from "json5"; import JSON5 from "json5";
import config from "../pynecone.json"; import env from "env.json";
const UPLOAD = config.uploadUrl; const PINGURL = env.pingUrl
const EVENTURL = env.eventUrl
const UPLOADURL = env.uploadUrl
// Global variable to hold the token. // Global variable to hold the token.
let token; let token;
@ -121,7 +123,7 @@ export const applyEvent = async (event, router, socket) => {
*/ */
export const applyRestEvent = async (queue_event, state, setResult) => { export const applyRestEvent = async (queue_event, state, setResult) => {
if (queue_event.handler == "uploadFiles") { if (queue_event.handler == "uploadFiles") {
await uploadFiles(state, setResult, queue_event.name, UPLOAD); await uploadFiles(state, setResult, queue_event.name);
} }
}; };
@ -184,13 +186,12 @@ export const connect = async (
result, result,
setResult, setResult,
router, router,
endpoint,
transports transports
) => { ) => {
// Get backend URL object from the endpoint // Get backend URL object from the endpoint
const endpoint_url = new URL(endpoint); const endpoint_url = new URL(EVENTURL);
// Create the socket. // Create the socket.
socket.current = io(endpoint, { socket.current = io(EVENTURL, {
path: endpoint_url["pathname"], path: endpoint_url["pathname"],
transports: transports, transports: transports,
autoUnref: false, autoUnref: false,
@ -221,7 +222,7 @@ export const connect = async (
* @param handler The handler to use. * @param handler The handler to use.
* @param endpoint The endpoint to upload to. * @param endpoint The endpoint to upload to.
*/ */
export const uploadFiles = async (state, setResult, handler, endpoint) => { export const uploadFiles = async (state, setResult, handler) => {
const files = state.files; const files = state.files;
// return if there's no file to upload // return if there's no file to upload
@ -244,7 +245,7 @@ export const uploadFiles = async (state, setResult, handler, endpoint) => {
} }
// Send the file to the server. // Send the file to the server.
await axios.post(endpoint, formdata, headers).then((response) => { await axios.post(UPLOADURL, formdata, headers).then((response) => {
// Apply the delta and set the result. // Apply the delta and set the result.
const update = response.data; const update = response.data;
applyDelta(state, update.delta); applyDelta(state, update.delta);

View File

@ -79,9 +79,6 @@ def _compile_page(component: Component, state: Type[State]) -> str:
return templates.PAGE.render( return templates.PAGE.render(
imports=imports, imports=imports,
custom_codes=component.get_custom_code(), custom_codes=component.get_custom_code(),
endpoints={
constant.name: constant.get_url() for constant in constants.Endpoint
},
initial_state=utils.compile_state(state), initial_state=utils.compile_state(state),
state_name=state.get_name(), state_name=state.get_name(),
hooks=component.get_hooks(), hooks=component.get_hooks(),

View File

@ -1,7 +1,7 @@
"""Create a list of components from an iterable.""" """Create a list of components from an iterable."""
from __future__ import annotations from __future__ import annotations
from typing import Any, Callable, Dict, List, Set, Tuple, Union from typing import Any, Callable, Iterable
from pynecone.components.component import Component from pynecone.components.component import Component
from pynecone.components.layout.fragment import Fragment from pynecone.components.layout.fragment import Fragment
@ -13,15 +13,13 @@ class Foreach(Component):
"""A component that takes in an iterable and a render function and renders a list of components.""" """A component that takes in an iterable and a render function and renders a list of components."""
# The iterable to create components from. # The iterable to create components from.
iterable: Var[Union[List, Dict, Tuple, Set]] iterable: Var[Iterable]
# A function from the render args to the component. # A function from the render args to the component.
render_fn: Callable = Fragment.create render_fn: Callable = Fragment.create
@classmethod @classmethod
def create( def create(cls, iterable: Var[Iterable], render_fn: Callable, **props) -> Foreach:
cls, iterable: Var[Union[List, Dict, Tuple, Set]], render_fn: Callable, **props
) -> Foreach:
"""Create a foreach component. """Create a foreach component.
Args: Args:

View File

@ -58,7 +58,7 @@ NODE_MODULES = "node_modules"
PACKAGE_LOCK = "package-lock.json" PACKAGE_LOCK = "package-lock.json"
# The pcversion app file. # The pcversion app file.
PCVERSION_APP_FILE = os.path.join(WEB_DIR, "pynecone.json") PCVERSION_APP_FILE = os.path.join(WEB_DIR, "pynecone.json")
ENV_JSON = os.path.join(WEB_DIR, "env.json")
# Commands to run the app. # Commands to run the app.
# The frontend default port. # The frontend default port.

View File

@ -7,10 +7,7 @@ import os
import random import random
import subprocess import subprocess
from pathlib import Path from pathlib import Path
from typing import ( from typing import TYPE_CHECKING, Optional, Union
TYPE_CHECKING,
Optional,
)
from rich.progress import Progress from rich.progress import Progress
@ -22,32 +19,42 @@ if TYPE_CHECKING:
from pynecone.app import App from pynecone.app import App
def update_json_file(file_path, key, value): def update_json_file(file_path: str, update_dict: dict[str, Union[int, str]]):
"""Update the contents of a json file. """Update the contents of a json file.
Args: Args:
file_path: the path to the JSON file. file_path: the path to the JSON file.
key: object key to update. update_dict: object to update json.
value: value of key.
""" """
with open(file_path) as f: # type: ignore fp = Path(file_path)
json_object = json.load(f) # create file if it doesn't exist
json_object[key] = value fp.touch(exist_ok=True)
with open(file_path, "w") as f: # create an empty json object if file is empty
fp.write_text("{}") if fp.stat().st_size == 0 else None
with open(fp) as f: # type: ignore
json_object: dict = json.load(f)
json_object.update(update_dict)
with open(fp, "w") as f:
json.dump(json_object, f, ensure_ascii=False) json.dump(json_object, f, ensure_ascii=False)
def set_pynecone_project_hash(): def set_pynecone_project_hash():
"""Write the hash of the Pynecone project to a PCVERSION_APP_FILE.""" """Write the hash of the Pynecone project to a PCVERSION_APP_FILE."""
update_json_file( update_json_file(
constants.PCVERSION_APP_FILE, "project_hash", random.getrandbits(128) constants.PCVERSION_APP_FILE, {"project_hash": random.getrandbits(128)}
) )
def set_pynecone_upload_endpoint(): def set_environment_variables():
"""Write the upload url to a PCVERSION_APP_FILE.""" """Write the upload url to a PCVERSION_APP_FILE."""
update_json_file( update_json_file(
constants.PCVERSION_APP_FILE, "uploadUrl", constants.Endpoint.UPLOAD.get_url() constants.ENV_JSON,
{
"uploadUrl": constants.Endpoint.UPLOAD.get_url(),
"eventUrl": constants.Endpoint.EVENT.get_url(),
"pingUrl": constants.Endpoint.PING.get_url(),
},
) )
@ -195,8 +202,8 @@ def setup_frontend(root: Path, disable_telemetry: bool = True):
dest=str(root / constants.WEB_ASSETS_DIR), dest=str(root / constants.WEB_ASSETS_DIR),
) )
# set the upload url in pynecone.json file # set the environment variables in client(env.json)
set_pynecone_upload_endpoint() set_environment_variables()
# Disable the Next telemetry. # Disable the Next telemetry.
if disable_telemetry: if disable_telemetry:

View File

@ -330,7 +330,7 @@ def test_setup_frontend(tmp_path, mocker):
assert str(web_folder) == prerequisites.create_web_directory(tmp_path) assert str(web_folder) == prerequisites.create_web_directory(tmp_path)
mocker.patch("pynecone.utils.prerequisites.install_frontend_packages") mocker.patch("pynecone.utils.prerequisites.install_frontend_packages")
mocker.patch("pynecone.utils.build.set_pynecone_upload_endpoint") mocker.patch("pynecone.utils.build.set_environment_variables")
build.setup_frontend(tmp_path, disable_telemetry=False) build.setup_frontend(tmp_path, disable_telemetry=False)
assert web_folder.exists() assert web_folder.exists()